Welcome!

Machine Learning Authors: Ed Featherston, Destiny Bertucci, Liz McMillan, Elizabeth White, Dan Blacharski

Related Topics: Java IoT

Java IoT: Article

Implementing Design Patterns in Java

Implementing Design Patterns in Java

The process of designing reusable object-oriented software is one of the hardest problems faced by object-oriented software designers. This is mainly due to the fact that different software architectures have different requirements. However, design patterns give the software designer the ability to reuse some successful designs that have been used in other projects and have proved to be successful. Thus, design patterns help software designers design successful new software by using prior successful designs as a basis for their new design.

Design Patterns are one of the most significant areas of emergence in object-oriented technology. Object-oriented software designers do not invent design patterns, but rather they discover them through experience. The usefulness of a design pattern won't be seen until it has been used and proven to be successful.

Because there are many design patterns out there, the authors of the Design Patterns[1] book classify patterns by two criteria, purpose and scope. The purpose criteria reflect what a pattern does. The scope criteria specify whether the pattern applies to classes or objects. Furthermore, the authors of the Design Patterns book organized three purposes for patterns: Creational, Structural or Behavioral. Creational patterns are concerned with the process of object creation. Structural patterns are concerned with the composition of classes or objects. Behavioral patterns specify the ways in which classes and objects interact and assign responsibilities.

Java Features
When using design patterns, solutions are expressed in objects and interfaces. Interfaces, Abstract Classes and Inheritance play a major role in implementing design patterns. The following is a review of these terms in Java.

Interfaces
An interface in Java consists of a series of declarations that are subject to two restrictions:
1. Method declarations (if any) must not include implementation code.
2. Variable declarations (if any) can have only constant initializers; that is variables declared static final.

For example, in the following interface:

interface Point {
void move(int x, int y);
}

Point is the name of the interface and move is a method declared inside the Point interface. Note that every interface is implicitly abstract, so the use of the abstract modifier is obsolete. Also, note that every field declaration in the body of an interface is implicitly public, static and final. Thus, it is redundant to specify any of these modifiers for such fields.

An interface in Java is used to identify a common set of methods and constants for the group of classes that implement the interface.

The interface(s) implemented by a class are identified in the "implements" clause of the class declaration. For example, the following class implements the Point interface declared above:

class Test implements Point {
void move(int x, int y) {
// implementation code goes here
}
}

Abstract Classes
An abstract class is a class that defines common behavior and has no direct instances; however, its descendant classes (known as concrete classes) have direct instances. Abstract classes may have abstract methods; that is, methods that are declared but not yet implemented. Thus, a class has abstract methods if any of the following conditions are valid:
1. It explicitly contains a declaration of an abstract method.
2. It inherits an abstract method from its direct superclass.
3. A direct superinterface of the class declares or inherits a method and that class does not contain a method that implements it.

Abstract classes should not be mixed with final classes in Java. A class is declared final if no subclasses are desired or required. Also note that if a class is declared final it cannot be declared abstract as well; otherwise, a compile-time error occurs.

As an example of an abstract class consider the following Employee class:

abstract class Employee {
abstract double compute_pay();
}
The abstract class Employee declares an abstract method, compute_pay. This concrete method defines only the form of the method without implementation; thus, each subclass must provide its own implementation.

NOTE: The abstract base class, Employee, could be coded as an interface. Using an interface instead of an abstract class might look cleaner since you don't have all those abstract keywords lying around.

Inheritance
In object-oriented languages, objects are defined in terms of classes, and classes can be defined in terms of other classes. For example, cars, trucks, buses and sport cars are all examples of vehicles. Classes can be organized into a hierarchy. A subclass inherits attributes from a superclass at a higher level in the tree. These attributes include state and behavior. Subclasses can add more variables and methods to the ones they inherit from the superclass; they can also override inherited methods by providing specialized implementations for those methods.

Classes in Java can have only one superclass. That is, Java has support for single inheritance but not multiple inheritance; however, note that a class may implement multiple interfaces.

As an example, Employees can be categorized in more than one class: consultants (hourly rate) and permanent employees (salary rate) for example. Thus, we can inherit from the Employee abstract class above as shown in Listing 1.

Figure 1 shows a class diagram representing this inheritance relationship.

Note about the figures: The figures were drawn with the Booch method's notation in mind. If a class has a small triangle with an "A" inside it, this means that the corresponding class is an Abstract Class.

Patterns
The following sections describe a case study using Java features (Interfaces, Abstract Classes, Inheritance, etc.) and object-oriented techniques (Design Patterns) to build extensible software.

The case study that we will consider is a graphics editor. The editor permits recursive groups of shapes to be constructed from circles, rectangles and triangles. Shapes that are not part of a group are root items and are available for manipulation. Constructing increasingly complex elements (groups of shapes) out of simple ones (shapes) is a technique called recursive composition. Note that we will not exploit all the patterns in this example. You may want to do that yourself as an exercise.

Factories
A Factory is an example of Creational Patterns. These patterns provide different ways to remove explicit references to concrete classes for code that needs to instantiate them. A class creational pattern class inheritance varies the class that is instantiated, while an object creational pattern delegates instantiation to another object. This is explained below through an example.

The shapes that our graphics editor will be capable of manipulating include circles, rectangles and triangles. Note that there is a common behavior with these shapes - all of them can be drawn, moved across the screen and erased. Thus, we can define Shape as an abstract class for all graphic elements that can appear in the graphics editor window. Its subclasses define primitive graphical elements such as circles, triangles and rectangles. Figure 2 depicts a representative part of the Shapes class hierarchy. The definition of the abstract Shape class looks like Listing 2.

NOTE: Shape can be an interface instead of an abstract class.

Note that the abstract class, Shape, cannot be instantiated. Thus, an attempt like

Shape shape = new Shape();

results in a compile-time error because abstract classes are not instantiable.

Abstract Factory
The abstract class, Shape, declared in Listing 2, is an example of the Abstract Factory Pattern. It declares an interface for creating each basic kind of shape (circle, rectangle, triangle). The participants in this pattern are Shape, which is the Abstract Factory, and Circle, Rectangle and Triangle where these classes implement operations to create concrete objects. These are known as Concrete Factories.

Shape is an abstract class that declares operations common to the graphic elements that our editor will manipulate. Thus, we can extend the Shape class for each graphic element and provide our own implementation. A sample implementation of the Circle class is shown in Listing 3.

The same thing goes for the Triangle and Rectangle shapes and is shown in Listing 4.

Factory Method
Another pattern along the lines of Abstract Factory is the Factory Method Pattern. This pattern encapsulates the knowledge of which shapes to create. For instance, when the user of the graphics editor clicks on the "Draw" pull-down menu, the event will determine which shape the user has selected. Then, the Factory Method Pattern is the one responsible for what kind of shape to produce depending on the number of arguments supplied as parameters to the Factory Method. Based on this definition, we can define a Factory Method Pattern that is capable of generating different shapes depending on the number (and type) of arguments supplied. A sample implementation of a Factory Method is shown in Listing 5.

The class DrawShapeFactory is an example of a Factory Method pattern. This factory generates shapes of different types depending on the number of arguments supplied. Note that the Factory Method pattern can also be implemented differently by having an abstract class, creator of shapes, and a concrete class for creating each shape. Figure 3 shows the structure of the Factory Method pattern.

An example of how to use the Factory of shapes is as follows:

Suppose we number the shapes: circle = 1, triangle = 2 and rectangle = 3.

Now, in the method where we handle mouse events we can check whether the Shape Number is 1, 2 or 3 and based on that we can generate different shapes. The code snippet in Listing 6 shows an example of use.

The design patterns mentioned above are not all the design patterns that can be found in a graphics editor application. You may want to check the Design Patterns book, which lists 23 design patterns, and try to exploit more patterns from the above case study. Applicable patterns include the command pattern, builder pattern, composite pattern, iterator pattern and observer pattern.

Other Design Patterns
The Adapter Pattern
The Adapter pattern is an example of structural patterns which are concerned with how classes and objects are composed to form larger structures. The Adapter pattern converts the interface of a class into another interface clients expect. For instance, if we were to add another feature, such as drawing text, to the graphics editor, then because of incompatibility we would create a new subclass of Shape and call it TextShape, for instance, and then we can implement our drawing text feature. Since we would be using an existing class, Shape, but the interface does not include text, then we would need an Adapter, in this case TextShape.

The Adapter pattern, plus some other patterns such as Visitor and Iterator, can be implemented using a new class of Java APIs from JavaSoft known as Inner Classes. Inner classes (or nested classes) are part of JDK1.1.

As a side point, note that people in the object-oriented programming community seem to have different views on inner classes. I believe that inner classes are contrary to good object-oriented design for the following reasons:
1. The inner class has access to the implementation of the outer class and thus information hiding is violated.
2. The inner class is dependent on the outer class. Thus, the inner class is not reusable.

The Iterator Pattern
The Iterator pattern is an example of behavioral patterns which are concerned with algorithms and the assignment of responsibilities between objects. The Iterator pattern, also known as Cursor, provides a way to access the elements of an aggregate object (e.g., array or a list) sequentially without exposing its internal structure.

For example, the "for" statement is normally used in conventional programming as the preferred means for structuring iteration over arrays. The following code snippet shows an example where we visit each element of array[i] to find the sum of the elements of the array:

for (int i = 0; i sum += array[i];
}

In this example, the aggregate array[] is processed element by element. The "for" statement specifies a specific order of visitation which is controlled by the index, i, that is visibly modified. The Iterator pattern can help in capturing the next element in the array with a next() member function, for example. Thus, the code for summing an array would look like

for (int i = 0; i <= array.length; ++i) {
sum += array.next();
}

Note how the index, i, is decoupled from visitation. Since i is not required for array indexing within the loop, it is unlikely that i gets modified accidently within the "for" loop. A more concrete example in Java is the Vector class in the package java.util package. Elements in a Vector object can be accessed using the nextElement() method of java.util.Enumeration. An analogous example to the above would be

for (Enumeration e = vector.elements(); e.hasMoreElements();) {
sum += ((Integer) e.nextElement()).intValue();
}

Successive calls to the nextElement() method return successive elements of the aggregate. An object that implements the Enumeration interface generates a series of elements, one at a time. Thus, depending on the task to be performed, an easy way to implement an Iterator pattern is to implement the Enumeration interface which provides methods to iterate through the elements of a vector, the keys of (and the values in) a hashtable.

The Observer Pattern
The Observer pattern is an example of Behavioral Patterns. It is a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. In the Observer pattern, there are subjects (or observables) that maintain some kind of state and observers that use the state represented by subjects. When a subject's state is changed, it informs one or more observers.

A variant of the Observer design pattern is supported by the Observer class in the java.util package. Each instance of this class maintains a set of observers that are notified whenever the Observable object changes in some significant way. An observer can be an object that implements interface Observer which is declared as

public interface Observer {
public void update(Observable o, Object arg);
}

The Observable class provides many useful methods, some of which include methods for adding and deleting observers, counting and notifying observers. The class is quite handy and easy to use.

Conclusion
One of the most significant areas of emergence in object-oriented technology is Design Patterns. Design Patterns represent solutions to problems that arise when developing software within a particular context. They facilitate reuse of prior successful software designs and improve key software quality factors, such as reuse, extensibility and performance. The material presented should give you a good introduction to design patterns and a start at implementing those design patterns in Java.

References:
1. Gamma, E., Helm, R., Johnson, R., and Vlissides J., "Design Patterns: Elements of Object-Oriented Architecture", Addison-Wesley, Reading, MA, 1995.
2. Rumbaugh, J., Blaha, M., Premerlani, W., Eddy, F., Lorensen, W., "Object-Oriented Modeling and Design", Prentice Hall, Englewood Cliffs, NJ, 1991.
3. Booch, G., "Object-Oriented Analysis and Design with Applications", 2nd edition. Benjamin/Cummings Publishing Inc., 1995.

More Stories By Qusay Mahmoud

Qusay H. Mahmoud is a graduate student in Computer Science at the University of New Brunswick, Saint John, Canada. This term he is teaching a course on Multimedia and the Information Highway at the university. As part of his thesis, he developed a Web-based distributedcomputing system using Java.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@CloudExpo Stories
As DevOps methodologies expand their reach across the enterprise, organizations face the daunting challenge of adapting related cloud strategies to ensure optimal alignment, from managing complexity to ensuring proper governance. How can culture, automation, legacy apps and even budget be reexamined to enable this ongoing shift within the modern software factory? In her Day 2 Keynote at @DevOpsSummit at 21st Cloud Expo, Aruna Ravichandran, VP, DevOps Solutions Marketing, CA Technologies, was jo...
"Storpool does only block-level storage so we do one thing extremely well. The growth in data is what drives the move to software-defined technologies in general and software-defined storage," explained Boyan Ivanov, CEO and co-founder at StorPool, in this SYS-CON.tv interview at 16th Cloud Expo, held June 9-11, 2015, at the Javits Center in New York City.
As Marc Andreessen says software is eating the world. Everything is rapidly moving toward being software-defined – from our phones and cars through our washing machines to the datacenter. However, there are larger challenges when implementing software defined on a larger scale - when building software defined infrastructure. In his session at 16th Cloud Expo, Boyan Ivanov, CEO of StorPool, provided some practical insights on what, how and why when implementing "software-defined" in the datacent...
Blockchain. A day doesn’t seem to go by without seeing articles and discussions about the technology. According to PwC executive Seamus Cushley, approximately $1.4B has been invested in blockchain just last year. In Gartner’s recent hype cycle for emerging technologies, blockchain is approaching the peak. It is considered by Gartner as one of the ‘Key platform-enabling technologies to track.’ While there is a lot of ‘hype vs reality’ discussions going on, there is no arguing that blockchain is b...
Blockchain is a shared, secure record of exchange that establishes trust, accountability and transparency across business networks. Supported by the Linux Foundation's open source, open-standards based Hyperledger Project, Blockchain has the potential to improve regulatory compliance, reduce cost as well as advance trade. Are you curious about how Blockchain is built for business? In her session at 21st Cloud Expo, René Bostic, Technical VP of the IBM Cloud Unit in North America, discussed the b...
You know you need the cloud, but you’re hesitant to simply dump everything at Amazon since you know that not all workloads are suitable for cloud. You know that you want the kind of ease of use and scalability that you get with public cloud, but your applications are architected in a way that makes the public cloud a non-starter. You’re looking at private cloud solutions based on hyperconverged infrastructure, but you’re concerned with the limits inherent in those technologies.
Is advanced scheduling in Kubernetes achievable?Yes, however, how do you properly accommodate every real-life scenario that a Kubernetes user might encounter? How do you leverage advanced scheduling techniques to shape and describe each scenario in easy-to-use rules and configurations? In his session at @DevOpsSummit at 21st Cloud Expo, Oleg Chunikhin, CTO at Kublr, answered these questions and demonstrated techniques for implementing advanced scheduling. For example, using spot instances and co...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
The cloud era has reached the stage where it is no longer a question of whether a company should migrate, but when. Enterprises have embraced the outsourcing of where their various applications are stored and who manages them, saving significant investment along the way. Plus, the cloud has become a defining competitive edge. Companies that fail to successfully adapt risk failure. The media, of course, continues to extol the virtues of the cloud, including how easy it is to get there. Migrating...
The use of containers by developers -- and now increasingly IT operators -- has grown from infatuation to deep and abiding love. But as with any long-term affair, the honeymoon soon leads to needing to live well together ... and maybe even getting some relationship help along the way. And so it goes with container orchestration and automation solutions, which are rapidly emerging as the means to maintain the bliss between rapid container adoption and broad container use among multiple cloud host...
Imagine if you will, a retail floor so densely packed with sensors that they can pick up the movements of insects scurrying across a store aisle. Or a component of a piece of factory equipment so well-instrumented that its digital twin provides resolution down to the micrometer.
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settle...
The need for greater agility and scalability necessitated the digital transformation in the form of following equation: monolithic to microservices to serverless architecture (FaaS). To keep up with the cut-throat competition, the organisations need to update their technology stack to make software development their differentiating factor. Thus microservices architecture emerged as a potential method to provide development teams with greater flexibility and other advantages, such as the abili...
Product connectivity goes hand and hand these days with increased use of personal data. New IoT devices are becoming more personalized than ever before. In his session at 22nd Cloud Expo | DXWorld Expo, Nicolas Fierro, CEO of MIMIR Blockchain Solutions, will discuss how in order to protect your data and privacy, IoT applications need to embrace Blockchain technology for a new level of product security never before seen - or needed.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
In his general session at 21st Cloud Expo, Greg Dumas, Calligo’s Vice President and G.M. of US operations, discussed the new Global Data Protection Regulation and how Calligo can help business stay compliant in digitally globalized world. Greg Dumas is Calligo's Vice President and G.M. of US operations. Calligo is an established service provider that provides an innovative platform for trusted cloud solutions. Calligo’s customers are typically most concerned about GDPR compliance, application p...
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...