JavaDesignPatternsAtaGlance
JavaDesignPatternsAtaGlance
1
Flyweight.............................................................................................................................................37
Definition.........................................................................................................................................37
Where to use & benefits..................................................................................................................37
Examples..........................................................................................................................................37
Proxy....................................................................................................................................................44
Definition.........................................................................................................................................44
Where to use & benefits..................................................................................................................44
Example...........................................................................................................................................44
Behavioral Patterns..............................................................................................................................45
Chain of Responsibility.......................................................................................................................45
Definition.........................................................................................................................................45
Where to use & benefits..................................................................................................................45
Example...........................................................................................................................................45
Command.............................................................................................................................................48
Definition.........................................................................................................................................48
Where to use & benefits..................................................................................................................49
Example...........................................................................................................................................49
Interpreter............................................................................................................................................52
Definition.........................................................................................................................................52
Where to use & benefits..................................................................................................................52
Example...........................................................................................................................................52
Iterator..................................................................................................................................................54
Definition.........................................................................................................................................54
Where to use & benefits..................................................................................................................54
Example...........................................................................................................................................54
Mediator...............................................................................................................................................57
Definition.........................................................................................................................................57
Where to use & benefits..................................................................................................................58
Example...........................................................................................................................................58
Observer...............................................................................................................................................62
Definition.........................................................................................................................................62
Where to use & benefits..................................................................................................................62
Example...........................................................................................................................................62
State.....................................................................................................................................................64
Definition.........................................................................................................................................64
Where to use & benefits..................................................................................................................65
Example...........................................................................................................................................65
Strategy................................................................................................................................................67
Definition.........................................................................................................................................67
Where to use & benefits..................................................................................................................67
Example...........................................................................................................................................68
Template Method.................................................................................................................................69
Definition.........................................................................................................................................69
Where to use & benefits..................................................................................................................69
Examples..........................................................................................................................................69
Visitor..................................................................................................................................................73
Definition.........................................................................................................................................73
Where to use & benefits..................................................................................................................73
Example...........................................................................................................................................73
J2EE Patterns.......................................................................................................................................76
2
MVC....................................................................................................................................................76
Definition.........................................................................................................................................76
Where to use & benefits..................................................................................................................76
History.............................................................................................................................................76
Core issue.........................................................................................................................................76
SCJD project design........................................................................................................................76
Business Delegate................................................................................................................................77
Definition.........................................................................................................................................77
Where to use & benefits..................................................................................................................77
Example...........................................................................................................................................77
Composite Entity.................................................................................................................................77
Definition.........................................................................................................................................77
Where to use & benefits..................................................................................................................78
Example...........................................................................................................................................78
Data Access Object..............................................................................................................................78
Definition.........................................................................................................................................78
Where to use & benefits..................................................................................................................78
Example...........................................................................................................................................79
Front Controller...................................................................................................................................79
Definition.........................................................................................................................................79
Where to use & benefits..................................................................................................................79
Example...........................................................................................................................................79
Intercepting Filter................................................................................................................................79
Definition.........................................................................................................................................80
Where to use & benefits..................................................................................................................80
Example...........................................................................................................................................80
Service Locator....................................................................................................................................81
Definition.........................................................................................................................................81
Where to use & benefits..................................................................................................................82
Example...........................................................................................................................................82
Transfer Object....................................................................................................................................82
Definition.........................................................................................................................................82
Where to use & benefits..................................................................................................................82
Example...........................................................................................................................................82
Misc.....................................................................................................................................................83
Typesafe Enum....................................................................................................................................83
Definition.........................................................................................................................................83
Where to use & benefits..................................................................................................................83
Example for jdk1.5..........................................................................................................................83
Example for type transfer for jdk1.5 below.....................................................................................85
Representational State Transfer (REST).............................................................................................87
Definition.........................................................................................................................................87
Where to use & benefits..................................................................................................................87
3
About Design Pattern
Many programmers with many years experience don't know design patterns, but as an Object-
Oriented programmer, you have to know them well, especially for new Java programmers. Actually,
when you solved a coding problem, you have used a design pattern. You may not use a popular
name to describe it or may not choose an effective way to better intellectually control over what you
built. Learning how the experienced developers to solve the coding problems and trying to use them
in your project are a best way to earn your experience and certification.
Remember that learning the design patterns will really change how you design your code; not only
will you be smarter but will you sound a lot smarter, too.
Note that the design patterns are not idioms or algorithms or components.
4
Generally, to build a system, you may need many patterns to fit together. Different designer may use
different patterns to solve the same problem. Usually:
References
Design Patterns -- Elements of Reusable Object-Oriented Software by GOF.
Return to top
Creational Patterns
Abstract Factory
Definition
Provides one level of interface higher than the factory pattern. It is used to return one of several
factories.
5
o Facade, which is often used with an abstract factory by providing an interface for
creating implementing class.
Example
Suppose you need to write a program to show data in two different places. Let's say from a local or a
remote database. You need to make a connection to a database before working on the data. In this
case, you have two choices, local or remote. You may use abstract factory design pattern to design
the interface in the following way:
class DataInfo {}
interface Local {
DataInfo[] loadDB(String filename);
}
6
return new RemoteMode();
}
public void loadData() {
if(local){
Local conn = getLocalConnection();
data = conn.loadDB("db.db");
}else {
Remote conn = getRemoteConnection();
conn.connect2WWW("www.some.where.com");
data = conn.loadDB("db.db");
}
}
// work on data
Such design is often used in SCJD project assignment. If you have a multiple places to load data,
you just add more methods in the connection interface without altering other structure, or add a
location variable in.
Return to top
7
Builder
Definition
Construct a complex object from simple objects step by step.
Example
To build a house, we will take several steps:
1. build foundation,
2. build frame,
3. build exterior,
4. build interior.
Let's use an abstract class HouseBuilder to define these 4 steps. Any subclass of HouseBuilder will
follow these 4 steps to build house (that is to say to implement these 4 methods in the subclass).
Then we use a WorkShop class to force the order of these 4 steps (that is to say that we have to build
interior after having finished first three steps). The TestBuilder class is used to test the coordination
of these classes and to check the building process.
import java.util.*;
class WorkShop {
//force the order of building process
public void construct(HouseBuilder hb) {
hb.buildFoundation();
hb.buildFrame();
hb.buildExterior();
hb.buildInterior();
}
}
8
abstract class HouseBuilder {
protected House house = new House();
9
class TwoStoryHouse extends HouseBuilder {
class House {
private String type = null;
private List features = new ArrayList();
public House() {
10
this.type = type;
}
class TestBuilder {
11
C:\ Command Prompt
C:\> javac TestBuilder.java
C:\>
To fine tune the above example, every do method can be designed as a class. Similar functional class
can be designed once and used by other classes. e.g. Window, Door, Kitchen, etc.
Another example, such as writing a Pizza program. Every gradient can be designed as a class. One
pizza at least consists of several gradients. Different pizza has different gradients. A builder pattern
may be adopted.
Return to top
Factory Method
Definition
Provides an abstraction or an interface and lets subclass or implementing classes decide which class
or method should be instantiated or called, based on the conditions or parameters given.
12
Follow naming conventions to help other developers to recognize the code structure.
Related patterns include
o Abstract Factory , which is a layer higher than a factory method.
o Template method, which defines a skeleton of an algorithm to defer some steps to
subclasses or avoid subclasses
o Prototype, which creates a new object by copying an instance, so it reduces
subclasses.
o Singleton, which makes a returned factory method unique.
Examples
To illustrate such concept, let's use a simple example. To paint a picture, you may need several steps.
A shape is an interface. Several implementing classes may be designed in the following way.
interface Shape {
public void draw();
}
class Line implements Shape {
Point x, y;
Line(Point a, Point b) {
x = a;
y = b;
}
public void draw() {
//draw a line;
}
}
class Square implements Shape {
Point start;
int width, height;
Square(Point s, int w, int h) {
start = s;
width = w;
height = h;
}
public void draw() {
//draw a square;
}
}
class Circle implements Shape {
....
}
class Painting {
Point x, y;
int width, height, radius;
Painting(Point a, Point b, int w, int h, int r) {
x = a;
y = b;
width = w;
height = h;
radius = r;
}
Shape drawLine() {
return new Line(x,y);
}
Shape drawSquare() {
13
return new Square(x, width, height);
}
Shape drawCircle() {
return new Circle(x, radius);
}
....
}
...
Shape pic;
Painting pt;
//initializing pt
....
if (line)
pic = pt.drawLine();
if (square)
pic = pt.drawSquare();
if (circle)
pic = pt.drawCircle();
From the above example, you may see that the Shape pic's type depends on the condition given. The
variable pic may be a line or square or a circle.
You may use several constructors with different parameters to instantiate the object you want. It is
another way to design with Factory pattern. For example,
class Painting {
...
Painting(Point a, Point b) {
new Line(a, b); //draw a line
}
Painting(Point a, int w, int h) {
new Square(a, w, h); //draw a square
}
Painting(Point a, int r){
new Circle(a, r); //draw a circle
}
...
}
You may use several methods to finish the drawing jobs. It is so-called factory method pattern. for
example,
class Painting {
...
Painting(Point a, Point b) {
draw(a, b); //draw a line
}
Painting(Point a, int w, int h) {
draw(a, w, h); //draw a square
}
Painting(Point a, int r){
draw(a, r); //draw a circle
}
...
14
}
Here is a popular example of Factory design pattern. For example, you have several database
storages located in several places. The program working on the database is the same. The user may
choose local mode or remote mode. The condition is the choice by the user. You may design your
program with Factory pattern. When the local mode is set, you may instantiate an object to work on
the local database. If the remote mode is set, you may instantiate an object which may have more job
to do like remote connection, downloading, etc.
interface DatabaseService {
public DataInfo getDataInfo() throws Exception;
public FieldInfo getFieldInfo() throws Exception;
public void write(FieldInfo fi) throws Exception;
public void modify(FieldInfo fi) throws Exception;
public void delete(FieldInfo fi) throws Exception;
//...
}
class Data implements DatabaseService {
To illustrate how to use factory design pattern with class level implementation, here is a real world
example. A company has a website to display testing result from a plain text file. Recently, the
company purchased a new machine which produces a binary data file, another new machine on the
way, it is possible that one will produce different data file. How to write a system to deal with such
change. The website just needs data to display. Your job is to provide the specified data format for
the website.
15
Here comes a solution. Use an interface type to converge the different data file format. The
following is a skeleton of implementation.
//load a file
public void load(String fileName);
16
System.exit(1);
C:\>java TestFactory 1
load from a txt file
txt file format changed
C:\>java TestFactory 2
load from an xml file
xml file format changed
C:\>java TestFactory 3
load from a db file
db file format changed
In the future, the company may add more data file with different format, a programmer just adds a
new class in accordingly. Such design saves a lot of code and is easy to maintain.
Return to top
Prototype
Definition
Cloning an object by reducing the cost of creation.
Example
17
Dynamic loading is a typical object-oriented feature and prototype example. For example, overriding
method is a kind of prototype pattern.
interface Shape {
public void draw();
}
class Line implements Shape {
public void draw() {
System.out.println("line");
}
}
class Square implements Shape {
public void draw() {
System.out.println("square");
}
}
class Circle implements Shape {
public void draw() {
System.out.println("circle");
}
}
class Painting {
public static void main(String[] args) {
Shape s1 = new Line();
Shape s2 = new Square();
Shape s3 = new Circle();
paint(s1);
paint(s2);
paint(s3);
}
static void paint(Shape s) {
s.draw();
}
}
----------------------------
If we want to make code more readable or do more stuff, we can code the paint
method in the following way:
The paint method takes a variable of Shape type at runtime. The draw method is called based on the
runtime type.
18
Overloading method is a kind of prototype too.
class Painting {
public void draw(Point p, Point p2) {
//draw a line
}
public void draw(Point p, int x, int y) {
//draw a square
}
public void draw(Point p, int x) {
//draw a circle
}
}
The draw method is called to draw the related shape based on the parameters it takes.
The prototype is typically used to clone an object, i.e. to make a copy of an object. When an object is
complicated or time consuming to be created , you may take prototype pattern to make such object
cloneable. Assume the Complex class is a complicated, you need to implement Cloneable interface
and override the clone method(protected Object clone()).
Cloning is a shallow copy of the original object. If the cloned object is changed, the original object
will be changed accordingly. See the following alteration.
19
try {
return super.clone();
}catch(CloneNotSupportedException cnse) {
System.out.println(cnse.getMessage());
return null;
}
}
int[] getNums() {
return nums;
}
}
class Test {
Complex c1 = new Complex();
Complex makeCopy() {
return (Complex)c1.clone();
}
public static void main(String[] args) {
Test tp = new Test();
Complex c2 = tp.makeCopy();
int[] mycopy = c2.getNums();
mycopy[0] = 5;
System.out.println();
System.out.print("local array: ");
for(int i = 0; i < mycopy.length; i++)
System.out.print(mycopy[i]);
System.out.println();
To avoid such side effect, you may use a deep copy instead of a shallow copy. The following shows
the alteration to the above example, note that the Complex class doesn't implement Cloneable
interface.
class Complex {
int[] nums = {1,2,3,4,5};
public Complex clone() {
return new Complex();
}
int[] getNums() {
return nums;
}
}
class Test2 {
Complex c1 = new Complex();
20
Complex makeCopy() {
return (Complex)c1.clone();
}
public static void main(String[] args) {
Test2 tp = new Test2();
Complex c2 = tp.makeCopy();
int[] mycopy = c2.getNums();
mycopy[0] = 5;
System.out.println();
System.out.print("local array: ");
for(int i = 0; i < mycopy.length; i++)
System.out.print(mycopy[i]);
System.out.println();
Return to top
Singleton
Definition
One instance of a class or one value accessible globally in an application.
21
o Builder, which is used to construct a complex object, whereas a singleton is used to
create a globally accessible object.
o Prototype, which is used to copy an object, or create an object from its prototype,
whereas a singleton is used to ensure that only one prototype is guaranteed.
Example
One file system, one window manager, one printer spooler, one Test engine, one Input/Output socket
and etc.
To design a Singleton class, you may need to make the class final like java.Math, which is not
allowed to subclass, or make a variable or method public and/or static, or make all constructors
private to prevent the compiler from creating a default one.
usage:
RemoteConnection rconn = RemoteConnection.getRemoteConnection;
rconn.loadData();
...
class Connection {
public static boolean haveOne = false;
public Connection() throws Exception{
if (!haveOne) {
doSomething();
haveOne = true;
}else {
throw new Exception("You cannot have a second instance");
}
}
public static Connection getConnection() throws Exception{
22
return new Connection();
}
void doSomething() {}
//...
public static void main(String [] args) {
try {
Connection con = new Connection(); //ok
}catch(Exception e) {
System.out.println("first: " +e.getMessage());
}
try {
Connection con2 = Connection.getConnection(); //failed.
}catch(Exception e) {
System.out.println("second: " +e.getMessage());
}
}
}
C:\ Command Prompt
C:\> java Connection
second: You cannot have a second instance
class Employee {
public static final int companyID = 12345;
public String address;
//...
}
class HourlyEmployee extends Employee {
public double hourlyRate;
//....
}
class SalaryEmployee extends Employee {
public double salary;
//...
}
class Test {
public static void main(String[] args) {
Employee Evens = new Employee();
HourlyEmployee Hellen = new HourlyEmployee();
SalaryEmployee Sara = new SalaryEmployee();
System.out.println(Evens.companyID == Hellen.companyID); //true
System.out.println(Evens.companyID == Sara.companyID); //true
}
}
C:\ Command Prompt
C:\> java Test
true
true
23
Note that Singletons are only guaranteed to be unique within a given class
loader. If you use the same class across multiple distinct enterprise
Whether you need to use synchronized keyword to manage the method access, it
depends on your project situation and thread controlling.
Return to top
Structural Patterns
Adapter
Definition
Convert the existing interfaces to a new interface to achieve compatibility and reusability of the
unrelated classes in one application. Also known as Wrapper pattern.
Example
24
The famous adapter classes in Java API are WindowAdapter,ComponentAdapter, ContainerAdapter,
FocusAdapter, KeyAdapter, MouseAdapter and MouseMotionAdapter.
As you know, WindowListner interface has seven methods. Whenever your class implements such
interface, you have to implements all of the seven methods. WindowAdapter class implements
WindowListener interface and make seven empty implementation. When you class subclass
WindowAdapter class, you may choose the method you want without restrictions. The following
give such an example.
import javax.swing.*;
import java.awt.event.*;
class Test extends JFrame {
public Test () {
setSize(200,200);
setVisible(true);
addWindowListener(new Closer());
}
public static void main(String[] args) {
new Test();
}
class Closer extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
}
To reuse classes and make new class compatible with existing ones. For example, A clean system is
already designed, you want to add more job in, the Extra interface uses adapter pattern to plug in the
existing system.
interface Clean {
public void makeClean();
}
class Office implements Clean{
25
public void makeClean() {
System.out.println("Clean Office");
}
}
class Workshop implements Clean{
public void makeClean() {
System.out.println("Clean Workshop");
}
}
class Test {
static void Jobs (Extra job) {
if (job instanceof Clean)
((Clean)job).makeClean();
if (job instanceof Extra)
((Extra)job).takeCare();
}
public static void main(String[] args) {
Extra e = new Facility();
Jobs(e);
Clean c1 = new Office();
Clean c2 = new Workshop();
c1.makeClean();
c2.makeClean();
e.makeClean();
}
}
C:\ Command Prompt
C:\> java Test
Clean Facility
Care has been taken
Clean Office
Clean Workshop
Clean Facility
By composition, we can achieve adapter pattern. It is also called wrapper. For example, a Data class
has already been designed and well tested. You want to adapt such class to your system. You may
declare it as a variable and wrapper or embed it into your class.
//well-tested class
class Data {
public void add(Info){}
public void delete(Info) {}
public void modify(Info){}
26
//...
}
Return to top
Bridge
Definition
Decouple an abstraction or interface from its implementation so that the two can vary independently.
Examples
If you have a question database, you may want to develop a program to display it based on the user
selection. The following is a simple example to show how to use a Bridge pattern to decouple the
relationship among the objects.
import java.util.*;
//abstraction
27
interface Question {
//implementation
class QuestionManager {
//further implementation
class QuestionFormat extends QuestionManager {
System.out.println("\n~~~~~~~~~~~~~~~~~~~~~~~~");
super.displayAll();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
28
//decoupled implementation
class JavaQuestions implements Question {
public JavaQuestions() {
//load from a database and fill in the container
questions.add("What is Java? ");
questions.add("What is an interface? ");
questions.add("What is cross-platform? ");
questions.add("What is UFT-8? ");
questions.add("What is abstract? ");
questions.add("What is Thread? ");
questions.add("What is multi-threading? ");
class TestBridge {
public static void main(String[] args) {
questions.display();
questions.next();
29
questions.newOne("What is object? ");
questions.newOne("What is reference type?");
questions.displayAll();
}
}
//need jdk1.5 to compile
C:\ Command Prompt
C:\> javac TestBridge.java
C:\> java TestBridge
What is Java?
~~~~~~~~~~~~~~~~~~~~~~~~
Question Catalog: Java Language
What is Java?
What is an interface?
What is cross-platform?
What is UFT-8?
What is abstract?
What is Thread?
What is multi-threading?
What is object?
What is reference type?
~~~~~~~~~~~~~~~~~~~~~~~~
C:\>
Note that the JavaQuestion class can be launched independently and work as its own system. Here
we just show you how to use Bridge pattern to decouple the interface from its implementation.
Return to top
Composite
Definition
Build a complex object out of elemental objects and itself like a tree structure.
30
o Flyweight, which is used with composite pattern to share components.
o Iterator, which is used to traverse the composites.
o Visitor, which localizes operations across composite and leaf classes.
Example
A component has many elements and itself which has many elements and itself, etc. A file system is
a typical example. Directory is a composite pattern. When you deal with Directory object, if isFile()
returns true, work on file, if isDirectory() returns true, work on Directory object.
class Directory {
Directory dir;
File[] f;
...
boolean isDirectory() {
return f == null;
}
boolean isFile() {
return f != null;
}
File getFile(int i) {
if (isFile())
return f[i];
return null'
}
Directory getDirectory() {
if (isDirectory())
return dir;
return null;
}
....
}
For example, General Manager may have several employees and some of employees are Managers
which have several employees. To illustrate such issue, we design a simple Manager class.
class Employee {
String name;
double salary;
Employee(String n, double s){
name = n;
salary = s;
}
String getName() {
return name;
}
double getSalary() {
return salary;
}
public String toString() {
return "Employee " + name;
}
}
class Manager {
Manager mgr;
Employee[] ely;
31
String dept;
Manager(Manager mgr,Employee[] e, String d ) {
this(e, d);
this.mgr = mgr;
}
Manager(Employee[] e, String d) {
ely = e;
dept =d;
}
String getDept() {
return dept;
}
Manager getManager() {
return mgr;
}
Employee[] getEmployee() {
return ely;
}
public String toString() {
return dept + " manager";
}
}
class Test {
public static void main(String[] args) {
Employee[] e1 = {new Employee("Aaron", 50),
new Employee("Betty", 60)};
Manager m1 = new Manager(e1, "Accounting");
System.out.println(m2);
Employee[] emp = m2.getEmployee();
if (emp != null)
for (int k = 0; k < emp.length; k++)
System.out.println(" "+emp[k]+" Salary: $"+
emp[k].getSalary());
Manager m = m2.getManager();
System.out.println(" " + m);
if (m!= null) {
Employee[] emps = m.getEmployee();
if (emps != null)
for (int k = 0; k < emps.length; k++)
System.out.println(" " + emps[k]+" Salary: $"+
emps[k].getSalary());
}
}
}
32
C:\ Command Prompt
C:\> java Test
Production manager
Employee Cathy Salary: $70.0
Employee Dan Salary: $80.0
Employee Eliz Salary: $90.0
Accounting manager
Employee Aaron Salary: $50.0
Employee Betty Salary: $60.0
Return to top
Decorator
Definition
Attach additional responsibilities or functions to an object dynamically or statically. Also known as
Wrapper.
Example
A JScrollPane object can be used to decorate a JTextArea object or a JEditorPane object. A window
can be decorated with different borders like BevelBorder, CompoundBorder, EtchedBorder
TitledBorder etc. These border classes working as decorators are provided in Java API.
33
Decorator pattern can be used in a non-visual fashion. For example, BufferedInputStream,
DataInputStream, and CheckedInputStream are decorating objects of FilterInputStream class. These
decorators are standard Java API classes.
To illustrate a simple decorator pattern in non-visual manner, we design a class that prints a number.
We create a decorator class that adds a text to the Number object to indicate that such number is a
random number. Of course we can subclass the Number class to achieve the same goal. But the
decorator pattern provides us an alternative way.
import java.util.Random;
class Number {
public void print() {
System.out.println(new Random().nextInt());
}
}
class Decorator {
public Decorator() {
System.out.print("Random number: ");//add a description to the number
printed
new Number().print();
}
}
class Test {
public static void main(String[] args) {
new Decorator();
new SubNumber();
}
}
java Test
Random number: 145265744
Random number: 145265755
Return to top
Façade
Definition
Make a complex system simpler by providing a unified or general interface, which is a higher layer
to these subsystems.
34
Want to reduce complexities of a system.
Decouple subsystems , reduce its dependency, and improve portability.
Make an entry point to your subsystems.
Minimize the communication and dependency between subsystems.
Security and performance consideration.
Shield clients from subsystem components.
Simplify generosity to specification.
Related patterns include
o Abstract Factory, which is often used to create an interface for a subsystem in an
independent way, and can be used as an alternative way to a facade.
o Singleton, which is often used with a facade.
o Mediator, which is similar to facade, but a facade doesn't define new functionality to
the subsystem.
Example
JDBC design is a good example of Façade pattern. A database design is complicated. JDBC is used
to connect the database and manipulate data without exposing details to the clients.
Security of a system may be designed with Façade pattern. Clients' authorization to access
information may be classified. General users may be allowed to access general information; special
guests may be allowed to access more information; administrators and executives may be allowed to
access the most important information. These subsystems may be generalized by one interface. The
identified users may be directed to the related subsystems.
interface General {
public void accessGeneral();
}
interface Special extends General {
public void accessSpecial();
}
interface Private extends General {
public void accessPrivate();
}
35
public void accessGeneral() {
// ...
}
//...
}
class Connection {
//...
The above code example illustrates that the whole system is not exposed to the clients. It depends on
the user classification.
Mr. SudHakar Chavali proposes a better design, similar to the above, but avoids repeated code. Look
at code below.
interface General {
public void accessGeneral();
}
//...
}
//...
}
//...
}
36
// ...
//...
}
To avoid repeated code, SpecialInfo become subclass of GeneralInfo and PrivateInfo becomes
subclass of SpecialInfo. When a person is exposed to special information, that person is allowed to
access general information also. When a person is exposed to private information, that person is
allowed to access general information and special information also.
When you design a mortgage process system, you may consider the process of checking client's
bank, credit and other loan information. Facade design may be a choice.
Return to top
Flyweight
Definition
Make instances of classes on the fly to improve performance efficiently, like individual characters or
icons on the screen.
Examples
In order to share an object, we may declare an interface and an intrinsic state through which
flyweights can receive and act on it. If you want to show a file system with folders to show the
37
directories or subdirectories, you don't need to load all the files or directories at one loading time.
You may show the upper level folders first. If the user clicks a folder, then load its subdirectories
and files. The shared trigger is mouse-clicked. The composite pattern may be combined to define the
flyweight system.
class Folder {
void draw(..) {}
}
class FolderFactory {
...
if (selected) {
return aFolder;
else
return aFile;
...
}
...
To show how to use flyweight to reduce object creation, we will make a program to draw 1000
circles with 6 different colors. Before we customize it to a flyweight design, it is coded as follows:
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public Test() {
Container contentPane = getContentPane();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Graphics g = panel.getGraphics();
38
}
Note that the above program doesn't take advantage of reusability of OOP. We will customize it and
make a Circle object, so the Circle object can be reused.
class Circle {
private Color color;
39
public void draw(Graphics g, int x, int y, int r) {
g.setColor(color);
g.drawOval(x, y, r, r);
}
}
Then we rewrite the program. It is possible for people to rewrite with Circle object in the following
way:
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public Test() {
Container contentPane = getContentPane();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
setSize(WIDTH ,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Graphics g = panel.getGraphics();
40
public static void main(String[] args) {
Test test = new Test();
}
}
From the above code, you may note that 1000 circle object has been created. It is memory
consuming.
To improve it, we will create a CircleFactory class to customize it by using flyweight design pattern.
Since we just draw circle with different colors, we can store color info in a hashmap. If a circle has
been drawn, the new circle will be checked with color. If the circle with the same color has been
found in the hashmap, the circle will share the instance which is picked up from the hashmap instead
of creating a new one. We will reuse the object with different state, that is to say we will share the
instance and draw the circle with different start position and radius on the fly.
class CircleFactory {
//store color
private static final HashMap circleByColor = new HashMap();
if(circle == null) {
circle = new Circle(color);
circleByColor.put(color, circle);
System.out.println("Creating " + color + " circle");//see how many
objects we create on command line
}
return circle;
}
}
import java.awt.*;
import java.util.HashMap;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public Test() {
Container contentPane = getContentPane();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
setSize(WIDTH,HEIGHT);
41
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Graphics g = panel.getGraphics();
for(int i=0; i < NUMBER_OF_CIRCLES; ++i) {
Circle circle = CircleFactory.getCircle(getRandomColor());
circle.draw(g, getRandomX(), getRandomY(),getRandomR());
//Since we have 6 different colors, we have 6 objects created.
}
}
});
}
public static void main(String[] args) {
Test test = new Test();
}
private int getRandomX() {
return (int)(Math.random()*WIDTH );
}
private int getRandomY() {
return (int)(Math.random()*HEIGHT);
}
private int getRandomR() {
return (int)(Math.random()*(HEIGHT/10));
}
private Color getRandomColor() {
return colors[(int)(Math.random()*colors.length)];
}
}
class CircleFactory {
private static final HashMap circleByColor = new HashMap();
if(circle == null) {
circle = new Circle(color);
circleByColor.put(color, circle);
System.out.println("Creating " + color + " circle");
}
return circle;
}
}
class Circle {
private Color color;
42
Copy, paste above code and run it. You will see the printout from the command line, that you only
have 6 objects created, not 1000 objects because you only have 6 colors. Such a big reduction of
object creation will improve your program performance dramatically.
Flyweight design is effective with instantiating a large amount of small and fine-grained classes by
combining with factory design pattern.
If you have jdk1.5 installed, you may need to use a tool to check if you save the memory by running
your commands as follows:
43
The jconsole tool will hook up your program Test to give your statistic numbers about your program,
such as threads, heap, memory, VM, etc.
String class is designed with Flyweight design pattern. It has similar structure as above example.
When you create a string constant, such constant is stored in a pool. When the second string is
created, it will be checked to see if it has been created. If it is true, the second string instance will be
picked up from the string pool instead of creating a new one. This is why the following code makes
sense, but bothers many people.
String s1 = "hello";
String s2 = "hello"; //store in a string pool.
String s3 = new String("hello");
Return to top
Proxy
Definition
Use a simple object to represent a complex one or provide a placeholder for another object to control
access to it.
Example
When loading a large image, you may create some light object to represent it until the image is
loaded completely. Usually a proxy object has the same methods as the object it represents. Once the
object is loaded, it passes on the actual object. For example,
44
...
}
class Image extends Graphic{
public void load() {
...
}
public void draw() {
...
}
...
}
class ImgProxy extends Graphic {
public void load() {
if(image == null) {
image = new Image(filename);
}
...
Return to top
Behavioral Patterns
Chain of Responsibility
Definition
Let more than one object handle a request without their knowing each other. Pass the request to
chained objects until it has been handled.
Example
45
The Java Servlet filter framework is an example of chain of resposibility design. Note that the
chain.doFilter() is the method that should be called to make the chain roll. If the subclass missed it,
the whole chain would be stopped or blocked.
Java exception handling is another example of chain of responsibility design. When an error occurs,
the exception call will look for a handling class. If there is no handler, the super Exception class will
be called to throw the exception. Otherwise, the handler class will handle it.
Here comes a simple example, just to show how chain of responsibility works. Whenever you spend
company's money, you need get approval from your boss, or your boss's boss. Let's say, the
leadership chain is:
Manager-->Director-->Vice President-->President
The following is a command line program to check who is responsible to approve your expenditure.
import java.io.*;
abstract class PurchasePower {
46
public void processRequest(PurchaseRequest request) {
if( request.getAmount() < ALLOWABLE )
System.out.println("Vice President will approve $" +
request.getAmount());
else
if( successor != null )
successor.processRequest(request);
}
}
class PurchaseRequest {
class CheckAuthority {
public static void main(String[] args){
ManagerPPower manager = new ManagerPPower();
DirectorPPower director = new DirectorPPower();
47
VicePresidentPPower vp = new VicePresidentPPower();
PresidentPPower president = new PresidentPPower();
manager.setSuccessor(director);
director.setSuccessor(vp);
vp.setSuccessor(president);
The composite pattern is often used with chain of responsibility. That means a class may contain the
related class that may handle the request.
Return to top
48
Command
Definition
Streamlize objects by providing an interface to encapsulate a request and make the interface
implemented by subclasses in order to parameterize the clients.
Example
The simple example of Command pattern is to design a Command interface and with an execute
method like this:
Then, design multiple implementation classes and see how powerful the execute() method has been
called dynamically.
In order to take advantage of Java built-in interfaces, we will design a window with a drop down
menu, button commands and popup menu with command pattern.
As we know, JButton, JMenuItem and JPopupMenu have constructors accept Action type variable.
Action interface extends ActionListener, which has the following hierarchy.
49
...
}
There is an abstract class called AbstractAction which implements Action interface. It has the
following design.
We will create several command classes to subclass the AbstractAction class and pass them to the
constructors of JButton, JMenuItem and JPopupMenu classes. There is a request method called
actionPerformed(), every command classes must implement it in order to make it work. To show the
concept, we just design two actions: submit and exit. You may expand such design to your need in
your future project.
Such action can be attached to any component, AWT or Swing. The caption, and Icon have been
designed as well as tooltips.
You can modify the program to add more commands in. These command classes are decoupled from
any program. It is very good for maintenance.
The whole workable program is as follows. You can run it to see the powerful command design
pattern.
50
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
51
private void showPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
pop.show(e.getComponent(),
e.getX(), e.getY());
}
}
});
JPanel jp = new JPanel();
JButton subbtn = new JButton(sa);
JButton exitbtn = new JButton(ea);
jp.add(subbtn);
jp.add(exitbtn);
Pay attention to the action buttons. The instances can be parameterized to JButton, JMenuItem and
JPopupMenu constructors. The powerful action design (Java built-in Action interface) makes objects
like ExitAction, SubmitAction be used everywhere. Design once, use everywhere.
Return to top
Interpreter
Definition
Provides a definition of a macro language or syntax and parsing into objects in a program.
52
o Iterator, which is used to traverse the tree structure.
o Visitor, which is used to maintain behavior of each note in tree structure.
Example
Given any string expression and a token, filter out the information you want. The below is a simple
parser program. the myParser method can be used to parse any expression. The composite, visit and
iterator patterns have been used.
import java.util.*;
class Parser{
private String expression;
private String token;
private List result;
private String interpreted;
53
String delimiter = "=,'";
Parser parser = new Parser(source, delimiter);
parser.myParser();
parser.interpret();
String result = parser.getInterpretedResult();
System.out.println(result);
}
}
java Parser
dest San Francisco origin Canada day MON
Return to top
Iterator
Definition
Provide a way to move through a list of collection or aggregated objects without knowing its internal
representations.
Example
Employee is an interface, Manager, PieceWorker, HourlyWorker and CommissionWorker are
implementation classes of interface Employee. EmployeeTest class will create a list and use a built-
in iterator of ArrayList class to traverse the members of the list.
import java.util.*;
interface Employee {
public abstract double earnings();
}
class Manager implements Employee {
private double weeklySalary;
private String name;
public Manager(String name, double s) {
54
this.name = name;
setWeeklySalary(s);
}
void setWeeklySalary(double s) {
if (s > 0) {
weeklySalary = s;
} else
weeklySalary = 0;
}
void setWagePerPiece(double w) {
if (w > 0)
wagePerPiece = w;
else
wagePerPiece = 0;
}
void setQuantity(int q) {
if ( q > 0)
quantity = q;
else
quantity = 0;
}
public String getName() {
return name;
}
public double earnings() {
return quantity * wagePerPiece;
}
55
public HourlyWorker(String name, double w, double h) {
this.name = name;
setHourlyWage(w);
setHours(h);
}
void setHourlyWage(double w) {
if (w > 0)
hourlyWage = w;
else
hourlyWage = 0;
}
void setHours(double h) {
if ( 0 <= h && h < 168)
hours = h;
else
hours = 0;
}
public String getName() {
return name;
}
public double earnings() {
return hourlyWage * hours;
}
public String toString() {
return "Hourly worker: " + getName();
}
}
56
return name;
}
public double earnings() {
return salary + commission/100*totalSales;
}
public String toString() {
return "Commission worker:"
+ getName();
}
}
class EmployeeTest {
public static void main(String[] args) {
java.util.List list = new ArrayList();
list.add(new Manager("Bill", 800.00));
list.add(new CommissionWorker("Newt", 400.0, 3.75, 159.99));
list.add(new PieceWorker("Al", 2.5, 200));
list.add(new HourlyWorker("Babara", 13.75, 40));
list.add(new Manager("Peter", 1200.00));
list.add(new CommissionWorker("Margret", 600.0,5.5, 200.25));
list.add(new PieceWorker("Mark", 4.5, 333));
list.add(new HourlyWorker("William", 31.25, 50));
The above example also shows a dynamic binding feature which is popular in Object-Oriented
realm.
If you want to pick up a specific object from the aggregated list, you may use the following code.
while(iterator.hasNext()) {
Employee em = (Employee)iterator.next();
if (em instanceof Manager) {
System.out.print(em + " earns $");
System.out.println(em.earnings());
}
}
The above list can also be replaced by an array and achieve the same result.
Return to top
57
Mediator
Definition
Define an object that encapsulates details and other objects interact with such object. The
relationships are loosely decoupled.
Example
If you have a complex GUI, whenever a button has been clicked, the related actions should be
disabled or enabled. You may design a Mediator class to include all related classes:
interface Command {
void execute();
}
class Mediator {
BtnView btnView;
BtnSearch btnSearch;
BtnBook btnBook;
LblDisplay show;
//....
void registerView(BtnView v) {
btnView = v;
}
void registerSearch(BtnSearch s) {
btnSearch = s;
}
void registerBook(BtnBook b) {
btnBook = b;
}
void registerDisplay(LblDisplay d) {
show = d;
}
58
void book() {
btnBook.setEnabled(false);
btnView.setEnabled(true);
btnSearch.setEnabled(true);
show.setText("booking...");
}
void view() {
btnView.setEnabled(false);
btnSearch.setEnabled(true);
btnBook.setEnabled(true);
show.setText("viewing...");
}
void search() {
btnSearch.setEnabled(false);
btnView.setEnabled(true);
btnBook.setEnabled(true);
show.setText("searching...");
}
}
Then, you may define classes which should be controlled by the Mediator class.
59
class LblDisplay extends JLabel{
Mediator med;
LblDisplay (Mediator m) {
super("Just start...");
med = m;
med.registerDisplay(this);
setFont(new Font("Arial",Font.BOLD,24));
}
}
From the above design, you can see that the relationships among the classes, which also known as
collegues or participating classes, are multidirectional. Mediator class contains all the information
about these classes and knows what these classes are going to do. The participating classes have to
register themselves to the Mediator class.
The MediatorDemo class will show the cooperation among the classes.
}
public void actionPerformed(ActionEvent ae) {
Command comd = (Command)ae.getSource();
comd.execute();
}
public static void main(String[] args) {
new MediatorDemo();
}
}
interface Command {
void execute();
}
class Mediator {
BtnView btnView;
BtnSearch btnSearch;
BtnBook btnBook;
LblDisplay show;
//....
void registerView(BtnView v) {
btnView = v;
}
void registerSearch(BtnSearch s) {
btnSearch = s;
}
void registerBook(BtnBook b) {
btnBook = b;
}
60
void registerDisplay(LblDisplay d) {
show = d;
}
void book() {
btnBook.setEnabled(false);
btnView.setEnabled(true);
btnSearch.setEnabled(true);
show.setText("booking...");
}
void view() {
btnView.setEnabled(false);
btnSearch.setEnabled(true);
btnBook.setEnabled(true);
show.setText("viewing...");
}
void search() {
btnSearch.setEnabled(false);
btnView.setEnabled(true);
btnBook.setEnabled(true);
show.setText("searching...");
}
}
class BtnView extends JButton implements Command {
Mediator med;
BtnView(ActionListener al, Mediator m) {
super("View");
addActionListener(al);
med = m;
med.registerView(this);
}
public void execute() {
med.view();
}
}
61
class LblDisplay extends JLabel{
Mediator med;
LblDisplay (Mediator m) {
super("Just start...");
med = m;
med.registerDisplay(this);
setFont(new Font("Arial",Font.BOLD,24));
}
}
class MediatorDemo extends JFrame implements ActionListener {
Mediator med = new Mediator();
MediatorDemo() {
JPanel p = new JPanel();
p.add(new BtnView(this,med));
p.add(new BtnBook(this,med));
p.add(new BtnSearch(this, med));
getContentPane().add(new LblDisplay(med), "North");
getContentPane().add(p, "South");
setSize(400,200);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
Command comd = (Command)ae.getSource();
comd.execute();
}
public static void main(String[] args) {
new MediatorDemo();
}
}
java MediatorDemo
Return to top
Observer
Definition
One object changes state, all of its dependents are updated automatically.
62
o Mediator, which is used to encapsulate updated objects.
Example
Observer pattern is often used in GUI application. For example, defining a one-to-many dependency
between objects so that when one object changes state, all its dependents are notified and updated
automatically, like stock change affecting many data or diagram updated accordingly.
Java API provides a built-in interface Observer and class Observable for use.
To show how observer pattern works, two windows have been created. One is for user input; another
is for display. When the data has been entered in the textfield, another window gets the message and
display it with a dialog. The private inner classes have been used in this example.
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
}
});
getContentPane().add(display);
setTitle("Observer form");
setSize(200,100);
setLocation(200,100);
setVisible(true);
63
public void doSomeUpdate() {
display.setText(inputForm.getText());
JOptionPane.showMessageDialog(DisplayForm.this,
"This form has been updated");
}
public static void main(String args[]) {
DisplayForm df = new DisplayForm();
}
}
class InputForm extends JFrame {
public InformDisplay inform = new InformDisplay();
//...
JTextField input= new JTextField(10);
public InputForm() {
JPanel panel= new JPanel();
input.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
inform.notifyObservers();
}
});
panel.add(new JLabel("Enter: "));
panel.add(input);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}});
getContentPane().add(panel);
setTitle("Observable form");
setSize(200,100);
setVisible(true);
}
public Observable getInputInfo() {
return inform;
}
Return to top
64
State
Definition
An object's behavior change is represented by its member classes, which share the same super class.
Example
To show the concept of State pattern, we use a simple command line program. If a GUI program is
used, a mediator pattern or a flyweight pattern may be applied on it.
Users connect to a database to do some jobs. Users from Management department may focus on
management. Users from Sales department may focus on sales information. Every connection has to
perform similar functions like open, log and close. Suppose we have an abstract Connection class
and have these functions listed. Thus, every subclass of Connection must implement these functions.
We list three subclasses Management, Sales and Accounting for example, just to show the State
pattern concept. The Controller class contains each state of connection. Its behavior is decided by
another object, which is a Test class. All the details have been hidden from the Test class. Suppose
we have a server which is a singleton. Which connection is made depends on the user. We use a Test
class which makes a trigger from command line. In the real program, the trigger should be made by
the user.
65
public void log() {
System.out.println("log activities");
}
//...
}
class Sales extends Connection {
public void open() {
System.out.println("open database for sales");
}
public void close() {
System.out.println("close the database");
}
public void log() {
System.out.println("log activities");
}
public void update() {
//
}
}
class Management extends Connection {
public void open() {
System.out.println("open database for management");
}
public void close() {
System.out.println("close the database");
}
public void log() {
System.out.println("log activities");
}
//...
}
class Controller {
public static Accounting acct;
public static Sales sales;
public static Management manage;
private static Connection current;
Controller() {
acct = new Accounting();
sales = new Sales();
manage = new Management();
}
public void makeAccountingConnection() {
current = acct;
}
public void makeSalesConnection() {
current = sales;
}
public void makeManagementConnection() {
current = manage;
}
public void open() {
current.open();
}
public void close() {
current.close();
}
public void log() {
current.log();
}
}
66
class Test {
String con;
Controller controller;
Test(String con) {
controller = new Controller();
//the following trigger should be made by the user
if(con.equalsIgnoreCase("management"))
controller.makeManagementConnection();
if(con.equalsIgnoreCase("sales"))
controller.makeSalesConnection();
if(con.equalsIgnoreCase("accounting"))
controller.makeAccountingConnection();
controller.open();
controller.log();
controller.close();
}
}
class Server {
public static Test test;
public static void main(String[] args) {
new Test(args[0]);
}
}
When we run the program with different connection, we will invoke the program in the following
printout:
Return to top
Strategy
Definition
Group several algorithms in a single module to provide alternatives. Also known as policy.
67
Need one of several algorithms dynamically.
The algorithms are exchangeable and vary independently
Configure a class with one of many related classes (behaviors).
Avoid exposing complex and algorithm-specific structures.
Data is transparent to the clients.
Reduce multiple conditional statements.
Provide an alternative to subclassing.
Related patterns include
State, which can activate several states, whereas a strategy can only activate one of
the algorithms.
o Flyweight, which provides a shared object that can be used in multiple contexts
simultaneously, whereas a strategy focuses on one context.
o Decorator, which changes the skin of an object, whereas a strategy changes the guts
of an object.
o Composite, which is used to combine with a strategy to improve efficiency.
Example
Compress files using different algorithms or save files in different formats or draw graphic in
different presentations. Here is a simple example. Just to show the concept of a strategy pattern.
interface FortuneCookies {
public void print();
}
class Five implements FortuneCookies {
public void print() {
System.out.println("It is your turn to get it");
}
}
class Two implements FortuneCookies {
public void print() {
System.out.println("It is never too late to start");
}
}
class Null implements FortuneCookies {
public void print() {
System.out.println("You got nothing");
}
}
class Dice {
public int throwIt() {
return (int)(Math.random()*6)+1;
}
}
//more class...
class Test {
static void goodFortune() {
int luckyNum = new Dice().throwIt();
FortuneCookies fc;
switch (luckyNum) {
case 2: fc = new Two();
break;
case 5: fc = new Five();
68
break;
//more
default: fc = new Null();
}
fc.print();
}
public static void main(String[] args) {
goodFortune();
}
}
Return to top
Template Method
Definition
Provide an abstract definition for a method or a class and redefine its behavior later or on the fly
without changing its structure.
Examples
For example, a loan application process may take several steps to finish. Let's assume the steps are
as follows:
You may use a template method to hold the process steps together without considering the real
implementation in the subclass.
69
abstract class CheckBackground {
//other methods
}
class TestTemplate {
public static void main(String[] args) {
70
System.out.println("\nCheck client " + mortgageClient.getName()+ "
Mortgage loan application. ");
mortgageClient.check();
C:\>
Method overloading and method overriding are good examples of template method pattern. For
example,
Coercion polymorphism -- refers to a single operation serving several types through implicit
type conversion.
Overloading polymorphism -- refers to using a single identifier for different operations.
Parametric polymorphism -- refers to a class declaration that allows the same field names and
method signatures to associate with a different type in each instance of that class.
The add() in the following code example is a template method. It can take any numerical primitive
types and the result can be casted to the type you want.
//coercion polymorphism
abstract class Add {
public abstract double add(double d1, double d2);//template
}
class AddAnyTypeNumber extends Add{
public double add(double d1, double d2) {
return d1 + d2;
}
}
class Test {
public static void main(String[] args) {
double d1 = 10.5, d2 = 9.5;
float f1 = 11.5f, f2 = 12.5f;
long l1 = 1, l2 = 2;
71
int i1 = 3, i2 = 4;
short s1 = 7, s2 = 8;
byte b1 = 5, b2 = 6;
System.out.println(addNumber.add(d1,d2));
System.out.println((float)addNumber.add(f1,f2));
System.out.println((long)addNumber.add(l1,l2));
System.out.println((int)addNumber.add(i1,i2));
System.out.println((short)addNumber.add(s1,s2));
System.out.println((byte)addNumber.add(b1,b2));
}
}
C:\ Command Prompt
C:\> java Test
20.0
24.0
3
7
15
11
Note that the side effect of using coercion polymorphism is casting in and casting out if you need
specific type to do the work. If you forget to do so, you may have unexpected result and it is hard to
debug.
If you don't have template method pattern concept or don't know Java type promotion technique, you
may write code in the following way:
72
class Test {
public static void main(String[] args) {
double d1 = 10.5, d2 = 9.5;
float f1 = 11.5f, f2 = 12.5f;
long l1 = 1, l2 = 2;
int i1 = 3, i2 = 4;
short s1 = 7, s2 = 8;
byte b1 = 5, b2 = 6;
System.out.println(addNumber.add(d1,d2));
System.out.println(addNumber.add(f1,f2));
System.out.println(addNumber.add(l1,l2));
System.out.println(addNumber.add(i1,i2));
System.out.println(addNumber.add(s1,s2));
System.out.println(addNumber.add(b1,b2));
}
}
C:\ Command Prompt
C:\> java Test
20.0
24.0
3
7
15
11
Without using template method pattern, you may write more lines of code. The good thing is that
you don't have any side effect by using specific designed method and you don't need to cast in or
out.
Return to top
Visitor
Definition
Define a new operation to deal with the classes of the elements without changing their structures.
73
Example
The following is a dummy program. Two interfaces involved: Visitor and Pizza. The Pizza system is
completely independent. "How to get it" tries to add new operations to the Pizza system. It is done
by adding another interface Visitor and parameterizing Pizza interface in the abstract method
visit(composite pattern). The "how to get" classes implement Visitor interface and make a
connection with Pizza system.
import java.util.*;
interface Visitor {
public void visit(Pizza p);
}
interface Pizza {
public String order();
}
class PopJohn implements Pizza {
final String name = "PopJohn";
public String order() {
return name;
}
}
class PizzaHut implements Pizza {
final String name = "PizzaHut";
public String order() {
return name;
}
}
class GodFather implements Pizza {
final String name = "GodFather";
public String order() {
return name;
}
}
class ByPickup implements Visitor {
private String name;
private final String method = "By pick up";
public void visit(Pizza p) {
name = p.order();
}
74
public void visit(Pizza p) {
name = p.order();
}
java Test
How many pizza restaurants in this area?
PopJohn
PizzaHut
75
GodFather
java Test
How many pizza restaurants in this area?
PopJohn
PizzaHut
GodFather
Return to top
J2EE Patterns
MVC
Definition
The Model/View/Controller(MVC) is an architecture design pattern. Model means data, View means
representation and Controller works on data and representation. MVC focuses on decouple the triad
relationships among data, representation and controller.
History
The Model/View/Controller(MVC) originates from Smalltalk, an OO programming language.
Core issue
76
MVC consists of three kind of objects. The Model is an internal representation of the data, the View
is the screen presentation of GUI, and the Controller coordinates changes between the Model and
View.
Try to visualize that the user reacts with the GUI, a DataManager(Controller) listens to the GUI's
call. If the user needs to load data, such request is sent to the DataManager, the DataManager starts
loading, searching and extracting the requested data from the server and sends it back to the GUI.
GUI is responsible to display data.
Here the server acts as Model, the DataManager acts as Controller and GUI acts as View. The
DataManager can be used for both remote and local modes (design two constructors for both
modes), the GUI can be replaced with any design and the data related classes can be packaged
together and put on local and server sides. All of the three objects can be reused for other projects
with little code alteration.
If you grasp such concept and skill, you will save a lot of time in designing and developing your
projects in the future. This is the so-called OOA/OOD.
Return to top
Business Delegate
Definition
An intermediate class decouples between presentation-tier clients and business services.
Example
77
Make a class deal with lookups and exception, acting as a representative of the client components
Return to top
Composite Entity
Definition
Use a coarse-grained interface to manage interactions between fine-grained or coarse-grained and
dependent objects internally. The Composite Entity is a coarse-grained entity bean. It may be the
coarse-grained object or hold a reference to the coarse-grained object. Also known as Aggregate
Entity.
Example
Return to top
Definition
78
Adapt a uniform interface to access multiple databases like relational, unrelational, object-oriented,
etc.
Example
See Sun's code sample
Return to top
Front Controller
Definition
Using a single component to process application requests.
79
Example
Design a servlet to deal with all the requests.
Return to top
Intercepting Filter
Definition
A pluggable component design to intercept incomming requests and outgoing responses, provide
common services in a standard manner (independently) without changing core processing code.
Example
To create a basic filter, you need to:
80
import javax.servlet.*;
import javax.servlet.http.*;
chain.doFilter(request, response);
}
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/xxx.jsp</url-pattern>
</filter-mapping>
You may use filter mapping and servlet mapping in web.xml file to diable the invoker servlet to
apply the filter.
Return to top
81
Service Locator
Definition
Centralizing distributed service object lookups, providing a centralized point of control, acting as a
cache that eliminates redundant lookups.
Example
Use a container as cache to hold the lookup object. One application only lookups same object once.
Doing so will dramatically improve performance. Make sure the container used is thread-safe.
Return to top
Transfer Object
Definition
Using a serializable class to act as data carrier, grouping related attributes, forming a composite
value and working as a return type from remote business method. Also known as Value object.
Example
82
In the J2EE server, the client tier may make several calls to retrieve data from the enterprise bean.
Even in the same machine, the every call from the client tier to the server tier is a remote method
call. Think about use Transfer Object design pattern to retrieve related attributes and return a single
object instead of each call just for retrieving a single attribute value. The transfer object is passed by
value to the client. All calls to the transfer object instance are local calls to the client, so such design
saves a lot of network traffic.
Let's say that you have a remote banking system. If the user has five requests one time, you should
design your system to give response once, not five times. You may need to group all return values
from these five requests to an object carrier and then return to client just once. Once the client
program receives the instance of this object, it invokes the accessors and gets value to display. The
total network traffic for one user just once.
Return to top
Misc
Typesafe Enum
Definition
Define a class representing a single element of the enumerated type and provide no public
constructor. An enumeration is a new type since Java 5 (jdk1.5). Before jdk1.4, you can create a
similar type that is much better and type safe. This is so-called Typesafe Enum pattern.
switch(coin) {
case PENNY: return 1;
case NICKEL: return 5;
83
case DIME: return 10;
case QUARTER: return 25;
default: return 0;
}
int value(){
switch(this) {
case PENNY: return 1;
case NICKEL: return 5;
case DIME: return 10;
case QUARTER: return 25;
default: return 0;
}
}
}
to use:
int v = coin.value();
Coin(int value){
coinValue = value;
}
}
84
//enum combining with visitor design pattern
public abstract class CoinVisitor {
void visitPenny(Coin c){}
void visitNickel(Coin c){}
void visitDime(Coin c){}
void visitQuarter(Coin c){}
}
typedef enum {
WHITE,
BLACK,
YELLOW
}color_t;
typedef enum {
CAMRY,
HONDA,
FORD
}car_t;
Once defined, an enumeration is used very much like an integer type. By default enumerator values
are assigned increasing from 0, so WHITE == 0, BLACK == 1 and YELLOW == 2, and so does for
enum car_t. You may see the following code:
The above code has a problem because the color and car have been mixed. Such type is not safe.
So let's see how Java does it. Use Java equivalent design, for example, define a playing card class,
you may try to do it in the following way,
85
}
The above code seems OK for switch statement, but is problematic and not type safe either.
Note that, the constructor is private, it prevents subclasses. The constants are static so they are easily
accessible. Such design makes a compile-time type safe.
You may use it somewhere like C's enum type in the following way:
Later, you want to expand Suit class, like the following, you don't need to recompile the client class.
86
public static final Suit SPADES =new Suit("spades");
Return to top
Definition
Representational State Transfer (REST) is a Web service design pattern. It is different from SOAP
based web services. REST services do not require XML, SOAP or WSDL service-API definitions.
The concept originally comes from a PhD's dissertation
CRUD:
87
For details see http://www.xfront.com/files/rest.html
Return to top
88