Docsity

Java design patterns, Summaries of Computer Science

Toggle sidebar
bg1
Java design patterns 101
Presented by developerWorks, your source for great tutorials
ibm.com/developerWorks
Table of Contents
If you're viewing this document online, you can click any of the topics below to link directly to that section.
1. About this tutorial....................................................... 2
2. Design patterns overview............................................. 4
3. A brief introduction to UML class diagrams........................ 8
4. Creational patterns..................................................... 10
5. Structural patterns...................................................... 12
6. Behavioral patterns .................................................... 15
7. Concurrency patterns.................................................. 18
8. Wrapup................................................................... 20
Java design patterns 101 Page 1 of 22
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16

Partial preview of the text

Download Java design patterns and more Summaries Computer Science in PDF only on Docsity!

Java design patterns 101

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Table of Contents

If you're viewing this document online, you can click any of the topics below to link directly to that section.

1. About this tutorial....................................................... 2

2. Design patterns overview ............................................. 4

3. A brief introduction to UML class diagrams ........................ 8

4. Creational patterns..................................................... 10

5. Structural patterns...................................................... 12

6. Behavioral patterns .................................................... 15

7. Concurrency patterns.................................................. 18

8. Wrapup................................................................... 20

Section 1. About this tutorial

Should I take this tutorial?

This tutorial is for Java programmers who want to learn about design patterns as a means of improving their object-oriented design and development skills. After reading this tutorial you will:

  • Understand what design patterns are and how they are described and categorized in several well-known catalogs

  • Be able to use design patterns as a vocabulary for understanding and discussing object-oriented software design

  • Understand a few of the most common design patterns and know when and how they should be used

This tutorial assumes that you are familiar with the Java language and with basic object-oriented concepts such as polymorphism, inheritance, and encapsulation. Some understanding of the Unified Modeling Language (UML) is helpful, but not required; this tutorial will provide an introduction to the basics.

What is this tutorial about?

Design patterns capture the experience of expert software developers, and present common recurring problems, their solutions, and the consequences of those solutions in methodical way.

This tutorial explains:

  • Why patterns are useful and important for object-oriented design and development
  • How patterns are documented, categorized, and cataloged
  • When patterns should be used
  • Some important patterns and how they are implemented

Tools

The examples in this tutorial are all written in the Java language. It is possible and sufficient to read the code as a mental exercise, but to try out the code requires a minimal Java development environment. A simple text editor (such as Notepad in Windows or vi in a UNIX environment) and the Java Development Kit (version 1.2 or later) are all you need.

A number of tools are also available for creating UML diagrams (see Resources on page 20 ). These are not necessary for this tutorial.

About the author

Section 2. Design patterns overview

A brief history of design patterns

Design patterns were first described by architect Christopher Alexander in his book A Pattern Language: Towns, Buildings, Construction (Oxford University Press, 1977). The concept he introduced and called patterns -- abstracting solutions to recurring design problems -- caught the attention of researchers in other fields, especially those developing object-oriented software in the mid-to-late 1980s.

Research into software design patterns led to what is probably the most influential book on object-oriented design: Design Patterns: Elements of Reusable Object-Oriented Software , by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley, 1995; see Resources on page 20 ). These authors are often referred to as the "Gang of Four" and the book is referred to as the Gang of Four (or GoF) book.

The largest part of Design Patterns is a catalog describing 23 design patterns. Other, more recent catalogs extend this repertoire and most importantly, extend coverage to more specialized types of problems. Mark Grand, in Patterns in Java: A Catalog of Reusable Design Patterns Illustrated with UML , adds patterns addressing problems involving concurrency, for example, and Core J2EE Patterns: Best Practices and Design Strategies by Deepak Alur, John Crupi, and Dan Malks focuses on patterns for multi-tier applications using Java 2 enterprise technologies.

There is an active pattern community that collects new patterns, continues research, and takes leads in spreading the word on patterns. In particular, the Hillside Group sponsors many conferences including one introducing newcomers to patterns under the guidance of experts. Resources on page 20 provides additional sources of information about patterns and the pattern community.

Pieces of a pattern

The Gang of Four described patterns as "a solution to a problem in a context". These three things -- problem, solution, and context -- are the essence of a pattern. For documenting the pattern it is additionally useful to give the pattern a name, to consider the consequences using the pattern will have, and to provide an example or examples.

Different catalogers use different templates to document their patterns. Different catalogers also use different names for the different parts of the pattern. Each catalog also varies somewhat in the level of detail and analysis devoted to each pattern. The next several panels describe the templates used in Design Patterns and in Patterns in Java.

Design Patterns template

Design Patterns uses the following template:

  • Pattern name and classification: A conceptual handle and category for the pattern

  • Intent: What problem does the pattern address?

  • Also known as: Other common names for the pattern

  • Motivation: A scenario that illustrates the problem

  • Applicability: In what situations can the pattern be used?

  • Structure: Diagram using the Object Modeling Technique (OMT)

  • Participants: Classes and objects in design

  • Collaborations: How classes and objects in the design collaborate

  • Consequences: What objectives does the pattern achieve? What are the tradeoffs?

  • Implementation: Implementation details to consider, language-specific issues

  • Sample code: Sample code in Smalltalk and C++

  • Known uses: Examples from the real world

  • Related patterns: Comparison and discussion of related patterns

Patterns in Java template

Patterns in Java uses the following template:

  • Pattern Name: The name and a reference to where it was first described

  • Synopsis: A very short description of the pattern

  • Context: A description of the problem the pattern is intended to solve

  • Forces: A description of the considerations that lead to the solution

  • Solution: A description of the general solution

  • Consequences: Implications of using the pattern

  • Implementation: Implementation details to consider

  • Java API Usage: When available, an example from the Java API is mentioned

  • Code example: A code example in the Java language

  • Related patterns: A list of related patterns

presentation logic from business. If all calls to the Internationalization API are isolated in a presentation module -- perhaps by wrapping them as JSP custom tags -- it would be redundant to add yet another layer of indirection.

Another example of when patterns should be used with care is discussed in Concurrency patterns on page 18 , regarding the consequences of the Single Thread Execution pattern.

As a system matures, as you gain experience, or flaws in the software come to light, it's good to occasionally reconsider choices you've made previously. You may have to rewrite ad hoc code so that it uses a pattern instead, or change from one pattern to another, or remove a pattern entirely to eliminate a layer of indirection. Embrace change (or at least prepare for it) because it's inevitable.

Section 3. A brief introduction to UML class diagrams

Class diagrams

UML has become the standard diagramming tool for object-oriented design. Of the various types of diagrams defined by UML, this tutorial only uses class diagrams. In class diagrams, classes are depicted as boxes with three compartments:

The top compartment contains the class name; if the class is abstract the name is italicized. The middle compartment contains the class attributes (also called properties , or variables). The bottom compartment contains the class methods (also called operations ). Like the class name, if a method is abstract, its name is italicized.

Depending on the level of detail desired, it is possible to omit the properties and show only the class name and its methods, or to omit both the properties and methods and show only the class name. This approach is common when the overall conceptual relationship is being illustrated.

Associations between classes

Any interaction between classes is depicted by a line drawn between the classes. A simple line indicates an association, usually a conceptual association of any unspecified type. The line can be modified to provide more specific information about the association. Navigability is indicated by adding an open arrowhead. Specialization , or subclassing, is indicated by adding a triangular arrowhead. Cardinal numbers (or an asterisk for an unspecified plurality) can also be added to each end to indicate relationships, such as one-to-one and many-to-one.

The following diagrams show these different types of associations:

Section 4. Creational patterns

Overview

Creational patterns prescribe the way that objects are created. These patterns are used when a decision must be made at the time a class is instantiated. Typically, the details of the classes that are instantiated -- what exactly they are, how, and when they are created -- are encapsulated by an abstract superclass and hidden from the client class, which knows only about the abstract class or the interface it implements. The specific type of the concrete class is typically unknown to the client class.

The Singleton pattern, for example, is used to encapsulate the creation of an object in order to maintain control over it. This not only ensures that only one is created, but also allows lazy instantiation; that is, the instantiation of the object can be delayed until it is actually needed. This is especially beneficial if the constructor needs to perform a costly operation, such as accessing a remote database.

The Singleton pattern

This code demonstrates how the Singleton pattern can be used to create a counter to provide unique sequential numbers, such as might be required for use as primary keys in a database:

// Sequence.java public class Sequence { private static Sequence instance; private static int counter; private Sequence() { counter = 0; // May be necessary to obtain // starting value elsewhere... } public static synchronized Sequence getInstance() { if(instance==null) // Lazy instantiation { instance = new Sequence(); } return instance; } public static synchronized int getNext() { return ++counter; } }

Some things to note about this implementation:

  • Synchronized methods are used to ensure that the class is thread-safe.

  • This class cannot be subclassed because the constructor is private. This may or may not be a good thing depending on the resource being protected. To allow subclassing, the visibility of the constructor should be changed to protected.

  • Object serialization can cause problems; if a Singleton is serialized and then deserialized more than once, there will be multiple objects and not a singleton.

The Factory Method pattern

In addition to the Singleton pattern, another common example of a creational pattern is the Factory Method. This pattern is used when it must be decided at run time which one of several compatible classes is to be instantiated. This pattern is used throughout the Java API. For example, the abstract Collator class's getInstance() method returns a collation object that is appropriate for the default locale, as determined by java.util.Locale.getDefault() :

Collator defaultCollator = getInstance();

The concrete class that is returned is actually always a subclass of Collator , RuleBasedCollator , but that is an unimportant implementation detail. The interface defined by the abstract Collator class is all that is required to use it.

The Proxy and Decorator patterns

A Proxy is a direct stand-in for another class, and it typically has the same interface as that class because it implements a common interface or an abstract class. The client object is not aware that it is using a proxy. A Proxy is used when access to the class the client would like to use must be mediated in a way that is apparent to the client -- because it requires restricted access or is a remote process, for example.

Decorator, like Proxy, is also a stand-in for another class, and it also has the same interface as that class, usually because it is a subclass. The intent is different, however. The purpose of the Decorator pattern is to extend the functionality of the original class in a way that is transparent to the client class.

Examples of the Decorator pattern in the Java API are found in the classes for processing input and output streams. BufferedReader() , for example, makes reading text from a file convenient and efficient:

BufferedReader in = new BufferedReader(new FileReader("file.txt"));

The Composite pattern

The Composite pattern prescribes recursive composition for complex objects. The intent is to allow all component objects to be treated in a consistent manner. All objects, simple and complex, that participate in this pattern derive from a common abstract component class that defines common behavior.

Forcing relationships into a part-whole hierarchy in this way minimizes the types of objects that our system (or client subsystem) needs to manage. A client of a paint program, for example, could ask a line to draw itself in the same way it would ask any other object, including a composite object.

d =Math.random(); if(d>0.75) { temp++; setChanged(); } else if (d<0.25) { temp--; setChanged(); } System.out.print("[Temp: " + temp + "]"); } public int getReading() { return temp; } } public class Display implements Observer { public void update(Observable o, Object arg) { System.out.print("New Temp: " + ((Sensor) o).getReading()); } public static void main(String []ac) { Sensor sensor = new Sensor(); Display display = new Display(); // register observer with observable class sensor.addObserver(display); // Simulate measuring temp over time for(int i=0; i < 20; i++) { sensor.takeReading(); sensor.notifyObservers(); System.out.println(); } } }

The Strategy and Template patterns

Strategy and Template patterns are similar in that they allow different implementations for a fixed set of behaviors. Their intents are different, however.

Strategy is used to allow different implementations of an algorithm, or operation, to be selected dynamically at run time. Typically, any common behavior is implemented in an abstract class and concrete subclasses provide the behavior that differs. The client is generally aware of the different strategies that are available and can choose between them.

For example, an abstract class, Sensor , could define taking measurements and concrete subclasses would be required to implement different techniques: one might provide a running average, another might provide an instantaneous measurement, and yet another might hold a peak (or low) value for some period of time.

The intention of the Template pattern is not to allow behavior to be implemented in different ways, as in Strategy, but rather to ensure that certain behaviors are implemented. In other words, where the focus of Strategy is to allow variety, the focus of Template is to enforce consistency.

The Template pattern is implemented as an abstract class and it is often used to provide a blueprint or an outline for concrete subclasses. Sometimes this is used to implement hooks in a system, such as an application framework.

synchronized works by locking the section of code when it is entered by one thread and blocking any other threads until the first thread is finished. If this is code used frequently by many threads, this could cause a serious degradation in performance.

Another danger is that two threads could become deadlocked if one thread is blocked at one critical section waiting for the second, while the second thread is blocked at another critical section, waiting for the first.

Section 8. Wrapup

Summary

Design patterns are a valuable tool for object-oriented design for a number of important reasons:

  • Patterns provide "...a solution to a problem in a context." ( Design Patterns , Gamma, Helm, Johnson, and Vlissides).

  • Patterns capture the expertise of experienced designers in a methodical way and make them available as design tools and learning tool for non-experts.

  • Patterns provide a vocabulary for discussing object-oriented design at a significant level of abstraction.

  • Patterns catalogs serve as a glossary of idioms that help in understanding common, but complex solutions to design problems.

Resources

Books

  • Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley, 1995) is probably the most influential resource on object-oriented design. Chapters 1, 2, and 6 are essential reading for understanding object-oriented design in general or, in particular, the role of patterns in object-oriented design.

  • Patterns in Java: A Catalog of Reusable Design Patterns Illustrated with UML by Mark Grand (Wiley, 1998) is not as well written as Design Patterns , especially regarding general object-oriented design issues, but the patterns in the catalog are easier to understand, particularly because the examples are written using the Java language and the recommendations address issues common for Java developers.

  • Core J2EE Patterns: Best Practices and Design Strategies by Deepak Alur, John Crupi, and Dan Malks (Prentice Hall, 2001) is a catalog of patterns for the design and architecture of multitier enterprise applications.

  • UML Distilled: Applying the Standard Object Modeling Language by Martin Fowler with Kendall Scott (Addison-Wesley, 2000) offers an excellent introduction to the essentials of UML. It includes a short but valuable discussion of using Class-Responsibility-Collaboration cards for object-oriented design.

  • The Unified Modeling Language User Guide by Grady Booch, Ivar Jacobson, and James Rumbaugh (Addison-Wesley, 1998) is helpful when you need more than just the essentials.

Web resources