Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

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.


@ThingsExpo Stories
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that SourceForge has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. SourceForge is the largest, most trusted destination for Open Source Software development, collaboration, discovery and download on the web serving over 32 million viewers, 150 million downloads and over 460,000 active development projects each and every month.
SYS-CON Events announced today that Nihon Micron will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...
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 impor...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
SYS-CON Events announced today that TidalScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
In a recent survey, Sumo Logic surveyed 1,500 customers who employ cloud services such as Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP). According to the survey, a quarter of the respondents have already deployed Docker containers and nearly as many (23 percent) are employing the AWS Lambda serverless computing framework. It’s clear: serverless is here to stay. The adoption does come with some needed changes, within both application development and operations. Tha...
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.