 | Level: Introductory Kunal Mittal (kunal@kunalmittal.com), Portal/J2EE Architect, Consultant
24 May 2005 This article introduces you to the basics of design patterns and explains how IBM Rational Software Architect fosters design pattern-based development. It also provides a few examples of design patterns and shows you how quickly you can build class diagrams and generate code based on these patterns. Follow-up articles will elaborate in more detail on what is covered in this introductory article.
A design pattern is a solution to a recurring design problem. A pattern describes how to solve the problem using a set of classes -- that is, it provides a general blueprint for a given part of your system. Patterns do not include algorithms; rather, they focus on the relationships between classes. By using design patterns, you are able to leverage proven solutions, which lead to better design and faster implementation. Design patterns also help the long-term maintainability of the code. The fundamental goals of a design pattern are to:
- Use interfaces
- Use composition rather than inheritance
- Encapsulate
For a different spin on why design patterns are important, consider the simple example of managing a list. In your computer science classes, you learned about different types of lists: arrays, hash maps, linked lists, stacks, queues, and so on. If you have programmed in the Java programming language, you've more than likely used the Collections interface and some of its subclasses. So, you know that all lists have one basic operation: iteration. You invariably want to iterate over a list to get the values stored in it. For a task such as this, I would use a simple design pattern such as Iterator, which focuses on the general functions of iterating over a list, to avoid re-inventing the wheel each time I wanted to traverse a list. The specific algorithm used to iterate over an array (versus a LinkedList) is left to the design pattern implementation.
Patterns were made popular by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides -- nicknamed the Gang of Four. Their authoritative book, Design Patterns: Elements Of Reusable Object-Oriented Software, is a must-read for any software architect. It defines 23 design patterns, all of which are included in Rational Software Architect. (For more information about the design patterns outlined by the Gang of Four, refer to the Resources section at the end of this article.) Today, almost every big information technology (IT) organization is working with design patterns. Sun Microsystems uses and exposes several design patterns in Java and Java 2 Platform Enterprise Edition (J2EE) technologies. The Server Side Web site is another good repository in which developers can contribute design patterns.
Elements of a design pattern
A design pattern is made up of the elements below. You can use this list as a template for reading or writing a design pattern:
- Pattern Name: A short, expressive name
- Intent: What the pattern does
- Also Known As: Other names used for this pattern
- Motivation: An example of a problem and how this pattern solves that problem
- Applicability: Scenarios to which this pattern applies
- Structure: Class diagrams that represent this pattern
- Participants: A description of the classes and their responsibilities
- Collaborations: Describes the interaction between the participants
- Consequences: Describes the trade-offs, design alternatives, and the impact of using this pattern
Whether creating your own patterns or using a pattern that already exists, make sure you pay close attention to the Applicability section. If you provide enough details in this section, other users will better understand when and how to use a design pattern that you've created. Conversely, this section will help you find the pattern that's most applicable to your specific design issue.
Types of design patterns
Rational Software Architect includes all 23 Gang of Four patterns in its repository. (However, you can also create and add your own patterns.) These patterns fall into three categories:
- Creational, which deal with the creation of objects or classes
- Behavioral, which deal with how classes or objects interact and distribute responsibilities
- Structural, which deal with the composition of the classes or objects
Figure 1 shows a complete list of the patterns available beneath each of these categories.
Figure 1. Design patterns available in Rational Software Architect
This article shows how to implement three basic design patterns in Rational Software Architect. The purpose of this article is not to make you an expert in design patterns but rather to show you the pattern capabilities that Rational Software Architect has.
Design patterns in Rational Software Architect
Rational Software Architect, which is part of the IBM Software Development Platform, allows architects to design and maintain application architecture. The tool is built on Eclipse, so developers and architects can leverage the usability features of the Eclipse Platform in Rational Software Architect. In addition, the tool goes beyond the features of a typical integrated development environment (IDE) by providing rich modeling and architectural design and discovery capabilities. This is where design patterns come in.
Note: For more information about Eclipse, see the Resources section. For more introductory information about Rational Software Architect, see my article "Introducing IBM Rational Software Architect: Improved usability makes software development easier"--also in the Resources section.
To show how simple it is to use design patterns in Rational Software Architect, I start by going through a simple pattern called the Singleton Pattern.
Note: The patterns I discuss in this article were chosen at random to address common tasks.
The Singleton Pattern
As its name suggests, the Singleton Pattern is typically used when you want only one instance of a particular class. For example, you could use this creational pattern if you wanted to generate unique keys for some database operations -- in this case, if you wanted only one instance of the class used to return these keys. Other instances in which this pattern is useful include logging and printing, such as when you want only one instance of a class to access and control one particular printer at a time.
To create an instance of the Singleton Pattern in Rational Software Architect, perform the following steps. (In this example, I don't focus on other issues related to this pattern, such as synchronization to make it thread safe.)
- Create a new Unified Modeling Language (UML) class diagram, then open the Pattern Explorer that Figure 1 above shows.
- Drag and drop the Singleton Pattern instance from the Pattern Explorer into the UML Class Diagram view.
- In the Pattern Parameters window, define a parameter called
MySingleton (see Figure 2). Doing so creates an instance of the Singleton Pattern in the Model Explorer.
- Drag and drop the instance onto the diagram.
- Create a private attribute for the Singleton Pattern called
_instance.
- Create two methods for the Singleton Pattern: The constructor is private, and there is one public method called
getInstance().
- Using the UML-Java transformation, generate the code for the Singleton Pattern (see Listing 1).
Figure 2. An instance of the Singleton Pattern
Listing 1.
Code generated for the Singleton Pattern
/*
* Created on Nov 20, 2004
*
* TODO To change the template for this generated file, go to
* Window - Preferences - Java - Code Style - Code Templates
*/
/**
* @author Kunal Mittal
*
* TODO To change the template for this generated type comment, go to
* Window - Preferences - Java - Code Style - Code Templates
* @uml.annotations
* derived_abstraction="platform:/resource/DesignPatternsProject/BlankModel.emx
* #_O5_0wDtjEdmuPoGm0fksdQ%2cuml2.Class%2cBlank+Model%3a%3aMySingleton"
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
public class MySingleton {
/**
* Comment for _instance
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private Object _instance;
/**
*
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private MySingleton() {
// TODO Auto-generated constructor stub
}
/**
*
*@generated "UML to Java (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
public void getInstance() {
// TODO Auto-generated method stub
}
}
|
Note: I discuss the instantiation of this pattern later in this article. For more information about creating UML class diagrams and UML-Java transformations, refer to my article "Introducing IBM Rational Software Architect: Improved usability makes software development easier" (see Resources).
That was a simple pattern. Now, I show you a slightly more complex pattern.
The Factory Method Pattern
The Factory Method Pattern is a creational pattern that defines an interface for creating an object but lets subclasses decide which actual class to instantiate. In other words, Factory Method lets a class defer the instantiation to its subclasses. This pattern is useful when an application is required to instantiate a class without the type of class being explicit. The class type will become explicit only when the application actually needs the class, not during compile or run time. The example that follows explains this concept further.
The pattern uses two types of classes: product classes and creator classes. Creator classes are used to define factory methods that create instances of the product objects. The product and create classes are abstract. Concrete classes provide the appropriate implementation for their respective base class. The Factory Method Pattern consists of the following classes:
- Creator: One class that acts like the creator
- ConcreteCreator: One or more concrete creators
- Product: An abstract product class
- ConcreteProduct: One or more concrete products
- FactoryMapping: Maps the creators to the products
To create an instance of the Factory Method Pattern, perform the same steps as for the Singleton Pattern. Figure 3 shows an example that I created. In this example, the pattern is made of the following classes:
- Creator: Game
- ConcreteCreator: BasicGame, AdvancedGame
- Product: Map
- ConcreteProduct: Room, Door, Wall, Window
- Factory Mapping: Create parameter relationships from Basic Game to Room, Door, and Wall. Create parameter relationships to all the concrete products from Advanced Game.
Figure 3. The Game Factory Method Pattern
Note: Before you generate the code and go through it, be aware that you also need to add the appropriate methods for the Factory Method Pattern.
In this example, the Game class cannot know when to instantiate the concrete game class until the player makes this choice. At that time, the Game class needs to create an instance of the BasicGame or the AdvancedGame class, as appropriate. This is a typical example of the Factory Method Pattern.
Another example for this pattern would be a library. A library has several documents, such as books, manuscripts, newspapers, and magazines. If you were building a library-management application, you wouldn't know what type of document a user was going to check out until the user brought the document to the librarian's desk. For practice, try using Rational Software Architect to model this pattern for a library.
You've seen two creational patterns. Now, let's look at how to use a behavioral pattern in Rational Software Architect.
The Chain of Responsibility Pattern
The Chain of Responsibility Pattern is used to promote loose coupling between the sender or initiator of a request (the client) and the system that is receiving the request. You would use the Chain of Responsibility Pattern when:
- More than one class needs to handle a particular request
- The order of the handlers needs to be specified dynamically
- The receiver of the request cannot be specified explicitly
The pattern allows you to chain the objects that can respond to the request. The client instantiates the request and passes it as a parameter to an instance of a handler. A concrete handler implements an action to take the request object and to maintain a reference to the next handler in the chain. An abstract handler is used from which concrete handlers extend. The elements of this pattern are:
- Handler: An abstract class
- ConcreteHandler: Concrete instances of the handler
- HandleRequest: The request handler
Take the example of an approval process. In this scenario, the client (in this case, a company's accounting department) submits a budget for approval. The budget needs to be approved by three people: the Chief Financial Officer (CFO), the Chief Operating Officer (COO), and the Chief Executive Officer (CEO). Figure 4 shows a simple example of this design pattern. In this example, the classes are:
- Handler: Approver
- ConcreteHandler: CEO, COO, CFO
- HandleRequest: ApproveBudget
Figure 4. Approval process Chain of Responsibility Pattern example
As another example, consider a customer support application. When a support call comes in to an IT department, it is first handled by the first-level support team. Based on their analysis of the call, they might need to forward the call to second- or third-level support personnel. Try modeling this scenario using the Chain of Responsibility Design Pattern in Rational Software Architect.
Summary
Design patterns are reusable solutions to common design issues. They help you create more maintainable software quickly. The 23 patterns described by the Gang of Four are built into Rational Software Architect, and you can drag and drop these patterns onto your diagrams and quickly set up your classes as described by the pattern. The code-generation feature in Rational Software Architect then allows you to generate code based on these patterns. In addition, you can also create your own patterns or implement patterns that others create.
In this article, you saw a few simple patterns and how you can implement them using Rational Software Architect. Although I chose three design patterns at random -- the Singleton Pattern, the Factory Method Pattern, and the Chain of Responsibility Pattern -- I recommend that you try to implement one or two other patterns using Rational Software Architect. Structural patterns are a great place to start. Another good exercise is to implement a design pattern that you might have read about or seen on some Web site, such as TheServerSide.com site or from the Sun Blueprints, within Rational Software Architect.
Resources - The article Introducing IBM Rational Software Architect: Improved usability makes software development easier (developerWorks, February 2005) is a basic introduction to the Rational Software Architect product.
- The tutorial Java design patterns 101 provides step-by-step instructions about using and creating design patterns.
- The article A Survey of Common Design Patterns gives an overview and explanation of several common design patterns.
- Check out the TheServerSide.com Patterns Page.
- Check out the Sun Microsystems Java Center for information about J2EE design patterns.
- Get the evaluation version of Rational Software Architect from the Trials and betas page
- For technical resources about Rational's products, visit the developerWorks Rational content area
. You'll find technical documentation, how-to articles, education, downloads, product information, and more. For specific information about Rational Software Architect, visit the RSA technical resources page.
- For details and more information about the Eclipse 3.0 platform, visit the Eclipse home page.
- Ask questions about Rational Software Architect in
the Rational Software Architect, Software Modeler, Application Developer and Web Developer forum.
- Read Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, which is available from Amazon.com
About the author  | 
|  | Kunal Mittal is a consultant specializing in Java™, Java 2 Platform, Enterprise Edition (J2EE), and Web services technologies. He is the co-author of and has contributed to several books on these topics. Kunal is currently working on a portal project for Sony Pictures Entertainment. For more information, visit his Web site at http://www.soaconsultant.com. |
Rate this page
|  |