Welcome!

Machine Learning Authors: Liz McMillan, Progress Blog, William Schmarzo, Madhavan Krishnan, VP, Cloud Solutions, Virtusa, Elizabeth White

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
"Infoblox does DNS, DHCP and IP address management for not only enterprise networks but cloud networks as well. Customers are looking for a single platform that can extend not only in their private enterprise environment but private cloud, public cloud, tracking all the IP space and everything that is going on in that environment," explained Steve Salo, Principal Systems Engineer at Infoblox, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventio...
Data scientists must access high-performance computing resources across a wide-area network. To achieve cloud-based HPC visualization, researchers must transfer datasets and visualization results efficiently. HPC clusters now compute GPU-accelerated visualization in the cloud cluster. To efficiently display results remotely, a high-performance, low-latency protocol transfers the display from the cluster to a remote desktop. Further, tools to easily mount remote datasets and efficiently transfer...
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
In his session at 21st Cloud Expo, James Henry, Co-CEO/CTO of Calgary Scientific Inc., introduced you to the challenges, solutions and benefits of training AI systems to solve visual problems with an emphasis on improving AIs with continuous training in the field. He explored applications in several industries and discussed technologies that allow the deployment of advanced visualization solutions to the cloud.
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"NetApp is known as a data management leader but we do a lot more than just data management on-prem with the data centers of our customers. We're also big in the hybrid cloud," explained Wes Talbert, Principal Architect at NetApp, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"We work around really protecting the confidentiality of information, and by doing so we've developed implementations of encryption through a patented process that is known as superencipherment," explained Richard Blech, CEO of Secure Channels Inc., in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, discussed how by using ne...
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, discussed how data centers of the future will be managed, how the p...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Codigm is based on the cloud and we are here to explore marketing opportunities in America. Our mission is to make an ecosystem of the SW environment that anyone can understand, learn, teach, and develop the SW on the cloud," explained Sung Tae Ryu, CEO of Codigm, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"We're focused on how to get some of the attributes that you would expect from an Amazon, Azure, Google, and doing that on-prem. We believe today that you can actually get those types of things done with certain architectures available in the market today," explained Steve Conner, VP of Sales at Cloudistics, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, provided a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to oper...
"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...
"We're developing a software that is based on the cloud environment and we are providing those services to corporations and the general public," explained Seungmin Kim, CEO/CTO of SM Systems Inc., in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.