Machine Learning Authors: Yeshim Deniz, Liz McMillan, Elizabeth White, Zakia Bouachraoui, Pat Romanski

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.

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.

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.

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.

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.

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.

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
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous importance on software-based innovations. They require not only skilled occupations, such as data analysts and DevOps professionals, with more technical skills, but also middle-level employees with more software and computing acumen. Both large and small firms operate differently.
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments that frequently get lost in the hype. The panel will discuss their perspective on what they see as they key challenges and/or impediments to adoption, and how they see those issues could be resolved or mitigated.
Most modern computer languages embed a lot of metadata in their application. We show how this goldmine of data from a runtime environment like production or staging can be used to increase profits. Adi conceptualized the Crosscode platform after spending over 25 years working for large enterprise companies like HP, Cisco, IBM, UHG and personally experiencing the challenges that prevent companies from quickly making changes to their technology, due to the complexity of their enterprise. An accomplished expert in Enterprise Architecture, Adi has also served as CxO advisor to numerous Fortune executives.
Eric Taylor, a former hacker, reveals what he's learned about cybersecurity. Taylor's life as a hacker began when he was just 12 years old and playing video games at home. Russian hackers are notorious for their hacking skills, but one American says he hacked a Russian cyber gang at just 15 years old. The government eventually caught up with Taylor and he pleaded guilty to posting the personal information on the internet, among other charges. Eric Taylor, who went by the nickname Cosmo the God, also posted personal information of celebrities and government officials, including Michelle Obama, former CIA director John Brennan, Kim Kardashian and Tiger Woods. Taylor recently became an advisor to cybersecurity start-up Path which helps companies make sure their websites are properly loading around the globe.