Académique Documents
Professionnel Documents
Culture Documents
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.
Creational Patterns
a. Abstract Factory
Definition
Provides one level of interface higher than the factory pattern. It is used to return one of several factories.
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);
}
}
// 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.
b. 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();
}
}
//set steps for building a house
abstract class HouseBuilder {
protected House house = new House();
class House {
private String type = null;
private List features = new ArrayList();
public House() {
class TestBuilder {
HouseBuilder one = new OneStoryHouse("2 bedrooms, 2.5 baths, 2-car garage, 1500
sqft");
HouseBuilder two = new TwoStoryHouse("4 bedrooms, 4 baths, 3-car garage, 5000
sqft");
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.
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.
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 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() {
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
}
...
}
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 {
public Data(String fileName) {...};
public Data(URL url, String fileName) {....};
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 DataManager{
Data data = null;
...
if (local) {
data = new Data(localFile);
...
}
if (remote){
data = new Data(connectRemote, databaseFile);
...
}
data.write(someInfo);
data.modify(someInfo);
....
}
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.
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);
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.
c. Prototype
Definition
Cloning an object by reducing the cost of creation.
Example
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();
}
The paint method takes a variable of Shape type at runtime. The draw method is called based on the
runtime type.
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()).
class Complex implements Cloneable {
int[] nums = {1,2,3,4,5};
public Object clone() {
try {
return super.clone();
}catch(CloneNotSupportedException cnse) {
System.out.println(cnse.getMessage());
return null;
}
}
int[] getNums() {
return nums;
}
}
class Test {
static Complex c1 = new Complex();
static Complex makeCopy() {
return (Complex)c1.clone();
}
public static void main(String[] args) {
Complex c1 = makeCopy();
int[] mycopy = c1.getNums();
for(int i = 0; i < mycopy.length; i++)
System.out.print(mycopy[i]);
}
}
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.
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();
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();
Singleton
Definition
One instance of a class or one value accessible globally in an application.
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{
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());
}
}
}
}
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
}
}
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.
Structural Patterns
a. 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
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{
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){}
//...
}
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
interface Question {
//implementation
class QuestionManager {
//further implementation
class QuestionFormat extends QuestionManager {
System.out.println("\n~~~~~~~~~~~~~~~~~~~~~~~~");
super.displayAll();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
//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();
questions.displayAll();
}
}
//need jdk1.5 to compile
~~~~~~~~~~~~~~~~~~~~~~~~
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.
b. Composite
Definition
Build a complex object out of elemental objects and itself like a tree structure.
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;
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());
}
}
}
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.
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
c. Façade
Definition
Make a complex system simpler by providing a unified or general interface, which is a higher layer to these
subsystems.
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();
}
class Connection {
//...
Mr. SudHakar Chavali proposes a better design, similar to the above, but avoids repeated code. Look at
code below.
interface General {
public void accessGeneral();
}
//...
}
//...
}
//...
}
// ...
//...
}
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.
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 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();
class Circle {
private Color color;
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();
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();
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;
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:
C:\> jconsole
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");
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,
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
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 {
class PurchaseRequest {
class CheckAuthority {
public static void main(String[] args){
ManagerPPower manager = new ManagerPPower();
DirectorPPower director = new DirectorPPower();
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.
b. 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.
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.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
});
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.
c. Interpreter
Definition
Provides a definition of a macro language or syntax and parsing into objects in a program.
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;
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) {
this.name = name;
setWeeklySalary(s);
}
void setWeeklySalary(double s) {
if (s > 0) {
weeklySalary = s;
} else
weeklySalary = 0;
}
public double earnings() {
return weeklySalary;
}
public String getName() {
return name;
}
public String toString() {
return "Manager: " + getName();
}
}
class PieceWorker implements Employee {
private double wagePerPiece;
private int quantity;
private String name;
public PieceWorker(String name, double w, int q) {
this.name = name;
setWagePerPiece(w);
setQuantity(q);
}
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;
}
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();
}
}
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.
e. 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;
}
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.
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();
}
}
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.
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();
}
}
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;
}
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();
}
}
}
public void actionPerformed(ActionEvent ae) {
Command comd = (Command)ae.getSource();
comd.execute();
}
public static void main(String[] args) {
new MediatorDemo();
}
}
java MediatorDemo
Memento
Definition
To record an object internal state without violating encapsulation and reclaim it later without knowledge of
the original object.
Example
To design a program with Memento feature is used to combine several design patterns like Command,
Mediator or Iterator.
class Memento {
int num;
Memento(int c) {
num = c;
}
int getNum() {
return num;
}
}
Then we combine Mediator and Command patterns to design three buttons and one label.The first button
throws dice, the second button shows the dice number backward, and the third button clears number
displayed. The label is used to display the dice number thrown. We use Math.random() method to get
number from 1 to 6.
The Mediator class will hold these participating objects and manipulate their relationships.
class Mediator {
BtnDice btnDice;
BtnPrevious btnPrevious;
BtnClear btnClear;
LblDisplay show;
java.util.List list, undo;
boolean restart = true;
int counter = 0, ct = 0;
//....
Mediator() {
list = new ArrayList();
undo = new ArrayList();
}
void registerDice(BtnDice d) {
btnDice = d;
}
void registerClear(BtnClear c) {
btnClear = c;
}
void registerPrevious(BtnPrevious p) {
btnPrevious = p;
}
void registerDisplay(LblDisplay d) {
show = d;
}
void throwit() {
show.setForeground(Color.black);
int num = (int)(Math.random()*6 +1);
int i = counter++;
list.add(i, new Integer(num));
undo.add(i, new Memento(num));
show.setText(""+num);
}
void previous() {
show.setForeground(Color.red);
btnDice.setEnabled(false);
if (undo.size() > 0) {
ct = undo.size()-1;
Memento num = (Memento)undo.get(ct);
show.setText(""+num.getNum());
undo.remove(ct);
}
if (undo.size() == 0)
show.setText("0");
}
void clear() {
list = new ArrayList();
undo = new ArrayList();
counter = 0;
show.setText("0");
btnDice.setEnabled(true);
}
}
The complete workable program is as follows. Copy it, compile it and run it.
import javax.swing.*;
import java.awt.event.*;
import java.awt.FontMetrics;
import java.awt.*;
import java.util.*;
import javax.swing.border.*;
interface Command {
void execute();
}
class Mediator {
BtnDice btnDice;
BtnPrevious btnPrevious;
BtnClear btnClear;
LblDisplay show;
java.util.List list, undo;
boolean restart = true;
int counter = 0, ct = 0;
//....
Mediator() {
list = new ArrayList();
undo = new ArrayList();
}
void registerDice(BtnDice d) {
btnDice = d;
}
void registerClear(BtnClear c) {
btnClear = c;
}
void registerPrevious(BtnPrevious p) {
btnPrevious = p;
}
void registerDisplay(LblDisplay d) {
show = d;
}
void throwit() {
show.setForeground(Color.black);
int num = (int)(Math.random()*6 +1);
int i = counter++;
list.add(i, new Integer(num));
undo.add(i, new Memento(num));
show.setText(""+num);
}
void previous() {
show.setForeground(Color.red);
btnDice.setEnabled(false);
if (undo.size() > 0) {
ct = undo.size()-1;
Memento num = (Memento)undo.get(ct);
show.setText(""+num.getNum());
undo.remove(ct);
}
if (undo.size() == 0)
show.setText("0");
}
void clear() {
list = new ArrayList();
undo = new ArrayList();
counter = 0;
show.setText("0");
btnDice.setEnabled(true);
}
}
class BtnDice extends JButton implements Command {
Mediator med;
BtnDice(ActionListener al, Mediator m) {
super("Throw Dice");
addActionListener(al);
med = m;
med.registerDice(this);
}
public void execute() {
med.throwit();
}
}
class BtnClear extends JButton implements Command {
Mediator med;
BtnClear(ActionListener al, Mediator m) {
super("Clear");
addActionListener(al);
med = m;
med.registerClear(this);
}
public void execute() {
med.clear();
}
}
class BtnPrevious extends JButton implements Command {
Mediator med;
BtnPrevious(ActionListener al, Mediator m) {
super("Previous");
addActionListener(al);
med = m;
med.registerPrevious(this);
}
public void execute() {
med.previous();
}
}
class Memento {
int num;
Memento(int c) {
num = c;
}
int getNum() {
return num;
}
}
class LblDisplay extends JLabel{
Mediator med;
LblDisplay (Mediator m) {
super("0",JLabel.CENTER);
med = m;
med.registerDisplay(this);
setBackground(Color.white);
setBorder(new EtchedBorder(Color.blue, Color.green));
Font font = new Font("Arial",Font.BOLD,40);
setFont(font);
}
}
class MementoDemo extends JFrame implements ActionListener {
Mediator med = new Mediator();
MementoDemo() {
JPanel p = new JPanel();
p.add(new BtnDice(this,med));
p.add(new BtnPrevious(this,med));
p.add(new BtnClear(this,med));
JPanel dice = new JPanel();
LblDisplay lbl = new LblDisplay(med);
dice.add(lbl);
getContentPane().add(dice, "Center");
getContentPane().add(p, "South");
setTitle("Memento pattern example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,200);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
Command comd = (Command)ae.getSource();
comd.execute();
}
public static void main(String[] args) {
new MementoDemo();
}
}
f. Observer
Definition
One object changes state, all of its dependents are updated automatically.
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);
}
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;
}
g. 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.
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();
}
}
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:
h. Strategy
Definition
Group several algorithms in a single module to provide alternatives. Also known as policy.
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();
break;
//more
default: fc = new Null();
}
fc.print();
}
public static void main(String[] args) {
goodFortune();
}
}
i. 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.
//other methods
}
class TestTemplate {
public static void main(String[] args) {
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;
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));
}
}
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:
abstract class Add {
public abstract double add(double d1, double d2);
public abstract float add(float d1, float d2);
public abstract long add(long d1, long d2);
public abstract int add(int d1, int d2);
public abstract short add(short d1, short d2);
public abstract byte add(byte d1, byte d2);
}
class AddNumber extends Add{
public double add(double d1, double d2) {
return d1 + d2;
}
public float add(float f1, float f2) {
return f1 + f2;
}
public long add(long l1, long l2) {
return l1 + l2;
}
public int add(int i1, int i2) {
return i1 + i2;
}
public short add(short s1, short s2) {
return (short)(s1 + s2);
}
public byte add(byte b1, byte b2) {
return (byte)(b1 + b2);
}
}
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));
}
}
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.
j. Visitor
Definition
Define a new operation to deal with the classes of the elements without changing their structures.
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();
}
java Test
How many pizza restaurants in this area?
PopJohn
PizzaHut
GodFather
java Test
How many pizza restaurants in this area?
PopJohn
PizzaHut
GodFather
J2EE Patterns
a. 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
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.
b. Business Delegate
Definition
An intermediate class decouples between presentation-tier clients and business services.
Where to use & benefits
• Simplify the complicated relationship.
• Reduce coupling.
• Cache results and references to remote business services.
• Cut potentially costly round trips
• Hide the underlying implementation details of business service.
• Related patterns include
o Proxy combined to simplify the complexity.
Example
Make a class deal with lookups and exception, acting as a representative of the client components.
c. 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.
Definition
Adapt a uniform interface to access multiple databases like relational, unrelational, object-oriented, etc.
Front Controller
Definition
Using a single component to process application requests.
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:
import javax.servlet.*;
import javax.servlet.http.*;
public class MyFilter implements Filter {
public void doFilter(ServletRequest request,
ServletResponse resonse,
FilterChain chain)
throws ServletException, IOException {
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.
f. 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.
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
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.
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;
case DIME: return 10;
case QUARTER: return 25;
default: return 0;
}
//enum type with a method
public enum Coin {
PENNY,
NICKEL,
DIME,
QUARTER;
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;
}
}
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,
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.
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: