design pattern by javacamp

Download Design Pattern by Javacamp

If you can't read please download the document

Upload: shivprakashjob14

Post on 25-Oct-2014

238 views

Category:

Documents


1 download

TRANSCRIPT

Java Design Pattern by javacamp

What is the design pattern? If a problem occurs over and over again, a solution to that problem has been used effectively. That solution is described as a pattern. The design patterns are languageindependent strategies for solving common object-oriented design problems. How many design patterns? The 23 design patterns by GOF are well known, and more are to be discovered on the way. Note that the design patterns are not idioms or algorithms or components.

What is the relationship among these patterns? 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:

Some patterns naturally fit together One pattern may lead to another Some patterns are similar and alternative Patterns are discoverable and documentable Patterns are not methods or framework Patterns give you hint to solve a problem effectively

List of al design patterns Creational Patterns --- Abstract Factory --- Builder --- Factory Method --- Prototype --- Singleton Structural Patterns --- Adapter --- Bridge --- Composite --- Decorator --- Faade --- Flyweight --- Proxy Behavioral Patterns --- Chain of Responsibility --- Command --- Interpreter --- Iterator --- Mediator --- Memento --- Observer --- State --- Strategy --- Template Method --- Visitor J2EE Patterns --- MVC --- Business Delegate --- Composite Entity --- Data Access Object --- Front Controller --- Intercepting Filter --- Service Locator --- Transfer Object Misc --- typesafe enum --- RESTful WS

Abstract Factory Provides one level of interface higher than the factory pattern. It is used to return one of several factories. Where to use & benefits

Creates families of related or dependent objects like Kit. Provides a class library of products, exposing interface not implementation. Needs to isolate concrete classes from their super classes. A system needs independent of how its products are created, composed, and represented. Try to enforce a constraint. An alternative to Facade to hide platform-specific classes Easily extensible to a system or a family Related patterns includeo o o o

Factory method, which is often implemented with an abstract factory. Singleton, which is often implemented with an abstract factory. Prototype, which is often implemented with an abstract factory. 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); } interface Remote extends Local{ void connect2WWW(String url); }

class LocalMode implements Local { public DataInfo[] loadDB(String name) { System.out.print("Load from a local database "); return null; } } class RemoteMode implements Remote { public void connect2WWW(String url) { System.out.println("Connect to a remote site "); } public DataInfo[] loadDB(String name) { System.out.println("Load from a remote database "); return null; } } // The Abstract Factory interface ConnectionFactory { Local getLocalConnection(); Remote getRemoteConnection(); } class DataManager implements ConnectionFactory { boolean local = false; DataInfo[] data; //... public Local getLocalConnection() { return new LocalMode(); } public Remote getRemoteConnection() { 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

public void setConnection(boolean b) { local = b; }

} //Use the following Test class to test the above classes class Test { public static void main(String[] args) { DataManager dm = new DataManager(); DataInfo[] di = null; String dbFileName = "db.db"; if (args.length == 1) { //assume local is set to true dm.setConnection(true); LocalMode lm = (LocalMode)dm.getLocalConnection(); di = lm.loadDB(dbFileName); } else { //Note: dm.local = false is default setting RemoteMode rm = (RemoteMode)dm.getRemoteConnection(); rm.connect2WWW("www.javacamp.org/db/"); di = rm.loadDB(dbFileName); } //use one set of methods to deal with loaded data. //You don't need to worry about connection from this point. //Like di.find(), di.search() etc. } } C:\ Command Prompt

C:\> java Test Connect to a remote site Load from a remote database C:\ Command Prompt

C:\> java Test local Load from a local database

Builder Construct a complex object from simple objects step by step.

Where to use & benefits

Make a complex object by specifying only its type and content. The built object is shielded from the details of its construction. Want to decouple the process of building a complex object from the parts that make up the object. Isolate code for construction and representation. Give you finer control over the construction process. Related patterns includeo

Abstract Factory, which focuses on the layer over the factory pattern (may be simple or complex), whereas a builder pattern focuses on building a complex object from other simple objects. Composite, which is often used to build a complex object.

o

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(); protected String showProgress() { return house.toString(); } abstract abstract abstract abstract } class OneStoryHouse extends HouseBuilder { public OneStoryHouse(String features) { house.setType(this.getClass() + " " + features); } public void buildFoundation() { //doEngineering() //doExcavating() //doPlumbingHeatingElectricity() //doSewerWaterHookUp() //doFoundationInspection() house.setProgress("foundation is done"); } public void buildFrame() { //doHeatingPlumbingRoof() //doElectricityRoute() //doDoorsWindows() //doFrameInspection() house.setProgress("frame is done"); } public void buildExterior() { //doOverheadDoors() //doBrickWorks() //doSidingsoffitsGutters() //doDrivewayGarageFloor() //doDeckRail() //doLandScaping() house.setProgress("Exterior is done"); } public void buildInterior() { //doAlarmPrewiring() public public public public void void void void buildFoundation(); buildFrame(); buildExterior(); buildInterior();

} }

//doBuiltinVacuum() //doInsulation() //doDryWall() //doPainting() //doLinoleum() //doCabinet() //doTileWork() //doLightFixtureBlinds() //doCleaning() //doInteriorInspection() house.setProgress("Interior is under going");

class TwoStoryHouse extends HouseBuilder { public TwoStoryHouse(String features) { house.setType(this.getClass() + " " + features); } public void buildFoundation() { //doEngineering() //doExcavating() //doPlumbingHeatingElectricity() //doSewerWaterHookUp() //doFoundationInspection() house.setProgress("foundation is done"); } public void buildFrame() { //doHeatingPlumbingRoof() //doElectricityRoute() //doDoorsWindows() //doFrameInspection() house.setProgress("frame is under construction"); } public void buildExterior() { //doOverheadDoors() //doBrickWorks() //doSidingsoffitsGutters() //doDrivewayGarageFloor() //doDeckRail() //doLandScaping() house.setProgress("Exterior is waiting to start"); } public void buildInterior() { //doAlarmPrewiring() //doBuiltinVacuum() //doInsulation()

} }

//doDryWall() //doPainting() //doLinoleum() //doCabinet() //doTileWork() //doLightFixtureBlinds() //doCleaning() //doInteriorInspection() house.setProgress("Interior is not started yet");

class House { private String type = null; private List features = new ArrayList(); public House() { } public House(String type) { this.type = type; } public void setType(String type) { this.type = type; } public String getType() { return type; } public void setProgress(String s) { features.add(s); } public String toString() { StringBuffer ff = new StringBuffer(); String t = type.substring(6); ff.append(t + "\n "); for (int i = 0; i < features.size(); i ++) { ff.append(features.get(i) + "\n "); } return ff.toString(); }

}

class TestBuilder { public static void main(String[] args) {

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"); WorkShop shop = new WorkShop(); shop.construct(one); shop.construct(two); System.out.println("Check house building progress: \n"); System.out.println(one.showProgress()); System.out.println(two.showProgress()); } //need jdk1.5 above to compile C:\ Command Prompt C:\> javac TestBuilder.java C:\> java TestBuilder Check house building progress: OneStoryHouse 2 bedrooms, 2.5 baths, 2-car garage, 1500 sqft foundation is done frame is done Exterior is done Interior is under going TwoStoryHouse 4 bedrooms, 4 baths, 3-car garage, 5000 sqft foundation is done frame is under construction Exterior is waiting to start Interior is not started yet 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. Where to use & benefits

Connect parallel class hierarchies. A class wants its subclasses to specify the object. A class cannot anticipate its subclasses, which must be created. A family of objects needs to be separated by using shared interface. The code needs to deal with interface, not implemented classes. Hide concrete classes from the client. Factory methods can be parameterized. The returned object may be either abstract or concrete object. Providing hooks for subclasses is more flexible than creating objects directly. Follow naming conventions to help other developers to recognize the code structure. Related patterns includeo o

Abstract Factory , which is a layer higher than a factory method. Template method, which defines a skeleton of an algorithm to defer some steps to subclasses or avoid subclasses Prototype, which creates a new object by copying an instance, so it reduces subclasses. Singleton, which makes a returned factory method unique.

o

o

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() { 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 }

}

...

The above draw() methods are overloaded. 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 public public public public public public //.... Data(String fileName) {...}; Data(URL url, String fileName) {....}; DataInfo getDataInfo() throws Exception {...}; FieldInfo getFieldInfo() throws Exception {...}; void write(FieldInfo fi) throws Exception {...}; void modify(FieldInfo fi) throws Exception {...}; 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. //Let's say the interface is Display interface Display { //load a file public void load(String fileName); //parse the file and make a consistent data type public void formatConsistency(); } //deal with plain text file class CSVFile implements Display{ public void load(String textfile) { System.out.println("load from a txt file"); } public void formatConsistency() { System.out.println("txt file format changed"); } } //deal with XML format file class XMLFile implements Display { public void load(String xmlfile) { System.out.println("load from an xml file"); } public void formatConsistency() { System.out.println("xml file format changed"); }

}

//deal with binary format file class DBFile implements Display { public void load(String dbfile) { System.out.println("load from a db file"); } public void formatConsistency() { System.out.println("db file format changed"); } } //Test the functionality

class TestFactory { public static void main(String[] args) { Display display = null; //use a command line data as a trigger if (args[0].equals("1")) display = new CSVFile(); else if (args[0].equals("2")) display = new XMLFile(); else if (args[0].equals("3")) display = new DBFile(); else System.exit(1); //converging code follows display.load(""); display.formatConsistency(); } } //after compilation and run it 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.

Prototype Definition Cloning an object by reducing the cost of creation. Where to use & benefits

When there are many subclasses that differ only in the kind of objects, A system needs independent of how its objects are created, composed, and represented. Dynamic binding or loading a method. Use one instance to finish job just by changing its state or parameters. Add and remove objects at runtime. Specify new objects by changing its structure. Configure an application with classes dynamically. Related patterns includeo

Abstract Factory, which is often used together with prototype. An abstract factory may store some prototypes for cloning and returning objects. Composite, which is often used with prototypes to make a part-whole relationship.

o

o

Decorator, which is used to add additional functionality to the prototype.

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(); } 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: static void paint(Shape s){ if ( s instanceof Line) s.draw(); //more job here if (s instanceof Square) s.draw(); //more job here if (s instanceof Circle) s.draw();

}

//more job here

C:\ Command Prompt C:\> java Painting line square circle The paint method takes a variable of Shape type at runtime. The draw method is called based on the runtime type. 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()). 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]); } } C:\ Command Prompt C:\> java Test 12345 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. 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 { 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(); System.out.print("cloned object: "); for(int ii = 0; ii < c2.nums.length; ii++) System.out.print(c2.nums[ii]); System.out.println();

}

System.out.print("original object: "); for(int iii = 0; iii < tp.c1.nums.length; iii++) System.out.print(tp.c1.nums[iii]);

C:\ Command Prompt C:\> java Test local array: 52345 cloned object: 52345 original object: 52345 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(); System.out.print("cloned object: "); for(int ii = 0; ii < c2.nums.length; ii++) System.out.print(c2.nums[ii]); System.out.println(); System.out.print("original object: "); for(int iii = 0; iii < tp.c1.nums.length; iii++) System.out.print(tp.c1.nums[iii]); }

} C:\ Command Prompt C:\> java Test2 local array: 52345 cloned object: 52345 original object: 12345

Singleton Definition One instance of a class or one value accessible globally in an application. Where to use & benefits

Ensure unique instance by defining class final to prevent cloning. May be extensible by the subclass by defining subclass final. Make a method or a variable public or/and static. Access to the instance by the way you provided. Well control the instantiation of a class. Define one value shared by all instances by making it static. Related patterns include

o o

Abstract factory, which is often used to return unique objects. Builder, which is used to construct a complex object, whereas a singleton is used to create a globally accessible object. 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.

o

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. For example, to make a unique remote connection, final class RemoteConnection { private Connect con; private static RemoteConnection rc = new RemoteConnection(connection); private RemoteConnection(Connect c) { con = c; .... } public static RemoteConnection getRemoteConnection() { return rc; } public void setConnection(Connect c) { this(c); } } usage: RemoteConnection rconn = RemoteConnection.getRemoteConnection; rconn.loadData(); ... The following statement may fail because of the private constructor RemoteConnection con = new RemoteConnection(connection); //failed //failed because you cannot subclass it (final class) class Connection extends RemoteConnection {} For example, to use a static variable to control the instance; 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()); } } } C:\ Command Prompt C:\> java Connection second: You cannot have a second instance For example to use a public static variable to ensure a unique. 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

The companyID is a unique and cannot be altered by all subclasses.

Note that Singletons are only guaranteed to be unique within a given class loader. If you use the same class across multiple distinct enterprise containers, you'll get one instance for each container. Whether you need to use synchronized keyword to manage the method access, it depends on your project situation and thread controlling.

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. Where to use & benefits

Try to match an interface(WindowAdapter, etc.) Make unrelated classes work together. Multiple compatibility. Increase transparency of classes. Make a pluggable kit. Delegate objects. Highly class reusable. Achieve the goal by inheritance or by composition Related patterns includeo

Proxy, which provides the same interface as its subject, whereas an adapter

provides a different interface to the object it adapts.o

Decorator, which focuses on adding new functions to an object, whereas an adapter coordinates two different objects. Bridge, which tries to separate an interface from its implementation and make an object vary independently, whereas an adapter tries to change and cooperate the interface of an object.

o

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. public interface Windowlistener { public void windowClosed(WindowEvent e); public void windowOpened(WindowEvent e); public void windowIconified(WindowEvent e); public void windowDeiconified(WindowEvent e); public void windowActivated(WindowEvent e); public void windowDeactivated(WindowEvent e); public void windowClosing(WindowEvent e); } public class WindowAdapter implements WindowListner{ public void windowClosed(WindowEvent e){} public void windowOpened(WindowEvent e){} public void windowIconified(WindowEvent e){} public void windowDeiconified(WindowEvent e){} public void windowActivated(WindowEvent e){} public void windowDeactivated(WindowEvent e){} public void windowClosing(WindowEvent e){} } Here is a test program 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"); } } interface Extra extends Clean{ public void takeCare(); } class Facility implements Extra{ public void makeClean() { System.out.println("Clean Facility"); } public void takeCare() { System.out.println("Care has been taken"); } } In order to reuse Workshop and Office classes, we create an adapter interface Extra and add new job takeCare in the system. 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 Data { public void public void public void //... } class add(Info){} delete(Info) {} modify(Info){}

//Use Data class in your own class class AdaptData { Data data; public void add(Info i) { data.add(i); //more job } public void delete(Info i) { data.delete(i); //more job } public void modify(Info i) { data.modify(i); //more job } //more stuff here //... }

Bridge Definition

Decouple an abstraction or interface from its implementation so that the two can vary independently. Where to use & benefits

Want to separate abstraction and implementation permanently Share an implementation among multiple objects Want to improve extensibility Hide implementation details from clients Related patterns includeo

Abstract Factory, which can be used to create and configure a particular bridge. Adapter, which makes unrelated classes work together, whereas a bridge makes a clear-cut between abstraction and implementation.

o

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 { public public public public public public void void void void void void nextQuestion(); priorQuestion(); newQuestion(String q); deleteQuestion(String q); displayQuestion(); displayAllQuestions();

}

//implementation class QuestionManager { protected Question questDB; //instantiate it later public String catalog; public QuestionManager(String catalog) { this.catalog = catalog; } public void next() { questDB.nextQuestion(); }

public void prior() { questDB.priorQuestion(); } public void newOne(String quest) { questDB.newQuestion(quest); } public void delete(String quest) { questDB.deleteQuestion(quest); } public void display() { questDB.displayQuestion(); } public void displayAll() { System.out.println("Question Catalog: " + catalog); questDB.displayAllQuestions(); }

}

//further implementation class QuestionFormat extends QuestionManager { public QuestionFormat(String catalog){ super(catalog); } public void displayAll() { System.out.println("\n~~~~~~~~~~~~~~~~~~~~~~~~"); super.displayAll(); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~"); } }

//decoupled implementation class JavaQuestions implements Question { private List questions = new ArrayList(); private int current = 0; 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 questions.add("What questions.add("What questions.add("What }

is is is is

UFT-8? "); abstract? "); Thread? "); multi-threading? ");

public void nextQuestion() { if( current 0 ) current--; } public void newQuestion(String quest) { questions.add(quest); } public void deleteQuestion(String quest) { questions.remove(quest); } public void displayQuestion() { System.out.println( questions.get(current) ); } public void displayAllQuestions() { for (String quest : questions) { System.out.println(quest); } } } class TestBridge { public static void main(String[] args) { QuestionFormat questions = new QuestionFormat("Java Language"); class questions.questDB = new JavaQuestions();//can be hooked up with other question //questions.questDB = new CsharpQuestions(); //questions.questDB = new CplusplusQuestions(); questions.display(); questions.next();

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.

Composite Definition Build a complex object out of elemental objects and itself like a tree structure. Where to use & benefits

Want to represent a part-whole relationship like tree folder system Group components to form larger components, which in turn can be grouped to form still larger components. Related patterns includeo

Decorator, which is often used with composite pattern and with the same parent class.

o o o

Flyweight, which is used with composite pattern to share components. Iterator, which is used to traverse the composites. 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; 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"); Employee[] e2 = {new Employee("Cathy", 70), new Employee("Dan", 80), new Employee("Eliz", 90)}; Manager m2 = new Manager(m1, e2, "Production"); 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()); } } 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 }

Decorator Definition Attach additional responsibilities or functions to an object dynamically or statically. Also known as Wrapper. Where to use & benefits

Provide an alternative to subclassing. Add new function to an object without affecting other objects. Make a responsibility easily added and removed dynamically. More flexibility than static inheritance. Transparent to the object. Related patterns includeo

Adapter pattern, which provides a different interface to the object it adapts, whereas a decorator changes an object's responsibilities, Proxy pattern, which controls access to the object, whereas a decorator focuses on adding new functions to an object, Composite pattern, which aggregates an object, whereas a decorator adds additional responsibilities to an object, and

o

o

o

Strategy pattern, which changes the guts of an object, whereas a decorator changes the skin of an object. Facade pattern, which provides a way of hiding a complex class, whereas a decorator adds function by wrapping a class.

o

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. 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 SubNumber extends Number{ public SubNumber() { super(); System.out.print("Random number: "); print(); } } class Test { public static void main(String[] args) { new Decorator(); new SubNumber(); } } java Test Random number: 145265744

Random number: 145265755

Faade Definition Make a complex system simpler by providing a unified or general interface, which is a higher layer to these subsystems. Where to use & benefits

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 includeo

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. Singleton, which is often used with a facade. Mediator, which is similar to facade, but a facade doesn't define new functionality to the subsystem.

o o

Example JDBC design is a good example of Faade 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 Faade 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 public } interface public General { void accessGeneral(); Special extends General { void accessSpecial();

} interface Private extends General { public void accessPrivate(); } class GeneralInfo implements General { public void accessGeneral() { //... } //... } class SpecialInfo implements Special{ public void accessSpecial() { //... } public void accessGeneral() {} //... } class PrivateInfo implements Private, Special { public void accessPrivate() { // ... } public void accessSpecial() { //... } public void accessGeneral() { // ... } //... } class Connection { //... if (user if (user if (user if (user //... is is is is unauthorized) throw new Exception(); general) return new GeneralInfo(); special) return new SpecialInfo(); executive) return new PrivateInfo();

}

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(); } interface Special extends General {

public void accessSpecial(); } interface Private extends General { public void accessPrivate(); } class GeneralInfo implements General { public void accessGeneral() { } //... } class SpecialInfo extends GeneralInfo implements Special{ public void accessSpecial() { } } class PrivateInfo extends SpecialInfo implements Private { public void accessPrivate() { // ... } //... } 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. Where to use & benefits

Need to instantiate a large amount of small and fine-grained classes. Need icons to represent object. An object extrinsic state can be shared by classes. Reduce the number of objects created, decrease memory footprint and increase performance. Increase runtime cost associated with transferring, finding, or computing extrinsic data. Related patterns includeo

Composite, which supports recursive structures, whereas an flyweight is often applied on it. Factory Method, which produces specific object upon requirement, whereas an flyweight uses it to reduce objects. State, which allows an object to alter its behavior when its internal state is changed, whereas a flyweight is best implemented on it. Strategy, which allows an algorithm vary independently to suit its needs, whereas a flyweight is based on such strategy.

o

o

o

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 import import import import java.awt.*; java.awt.Color; java.awt.event.*; javax.swing.*; javax.swing.event.*;

class Test extends JFrame{ private static final Color colors[] = { Color.red, Color.blue, Color.yellow, Color.orange, Color.black, Color.white }; private static final int WIDTH_ = 400, HEIGHT = 400, NUMBER_OF_CIRCLES = 1000; public Test() { Container contentPane = getContentPane(); JButton button = new JButton("Draw Circle"); final JPanel panel = new JPanel(); 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(); for(int i=0; i < NUMBER_OF_CIRCLES; ++i) { g.setColor(getRandomColor()); int r = getRandomR(); g.drawOval(getRandomX(), getRandomY(), r, r); } } }); } private int getRandomX() { return (int)(Math.random()*WIDTH ); } private int getRandomY() { return (int)(Math.random()*HEIGHT); }

} Copy, paste above code, and run it to see the functionality. C:\ Command Prompt C:\> java Test

private int getRandomR() { return (int)(Math.random()*(HEIGHT/10)); } private Color getRandomColor() { return colors[(int)(Math.random()*colors.length)]; } public static void main(String[] args) { Test test = new Test(); }

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; public Circle(Color color) { this.color = color; } 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 import import import import java.awt.*; java.awt.Color; java.awt.event.*; javax.swing.*; javax.swing.event.*;

class Test extends JFrame{ private static final Color colors[] = { Color.red, Color.blue, Color.yellow, Color.orange, Color.black, Color.white }; private static final int WIDTH = 400, HEIGHT = 400, NUMBER_OF_CIRCLES = 1000; public Test() { Container contentPane = getContentPane(); JButton button = new JButton("Draw Circle"); final JPanel panel = new JPanel(); 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(); for(int i=0; i < NUMBER_OF_CIRCLES; ++i) { Circle circle = new Circle(getRandomColor()); circle.draw(g, getRandomX(), getRandomY(), getRandomR());//1000 object created. } }); } 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)]; } 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(); public static Circle getCircle(Color color) { Circle circle = (Circle)circleByColor.get(color); 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; } } So our test program will be coded as follows: import import import import import import java.awt.*; java.util.HashMap; java.awt.Color; java.awt.event.*; javax.swing.*; javax.swing.event.*;

class Test extends JFrame{ private static final Color colors[] = { Color.red, Color.blue, Color.yellow, Color.orange, Color.black, Color.white }; private static final int WIDTH = 400, HEIGHT = 400, NUMBER_OF_CIRCLES = 1000;

public Test() { Container contentPane = getContentPane(); JButton button = new JButton("Draw Circle"); final JPanel panel = new JPanel(); 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(); 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(); public static Circle getCircle(Color color) { Circle circle = (Circle)circleByColor.get(color); if(circle == null) { circle = new Circle(color); circleByColor.put(color, circle);

} }

} return circle;

System.out.println("Creating " + color + " circle");

class Circle { private Color color; public Circle(Color color) { this.color = color; } public void draw(Graphics g, int x, int y, int r) { g.setColor(color); g.drawOval(x, y, r, r); } } 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. C:\ Command Prompt C:\> java Test Creating java.awt.Color[r=255,g=0,b=0] circle Creating java.awt.Color[r=0,g=0,b=0] circle Creating java.awt.Color[r=255,g=200,b=0] circle Creating java.awt.Color[r=255,g=255,b=0] circle Creating java.awt.Color[r=0,g=0,b=255] circle Creating java.awt.Color[r=255,g=255,b=255] circle

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:\ Command Prompt C:\> java -Dcom.sun.management.jmxremote Test And open another console as follows: C:\ Command Prompt 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");

System.out.println(s1==s2); //true, share the same memmory address System.out.println(s1==s3); //false

Proxy Definition Use a simple object to represent a complex one or provide a placeholder for another object to control access to it. Where to use & benefits

If creating an object is too expensive in time or memory. Postpone the creation until you need the actual object. Load a large image (time consuming). Load a remote object over network during peak periods. Access right is required to a complex system. Related patterns includeo

Adapter pattern, which provides a different interface to the object it adapts, whereas a proxy provides the same interface as its subject, and Decorator pattern, which focuses on adding new functions to an object, whereas a proxy controls access to the object.

o

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, abstract class Graphic { public abstract void load(); public abstract void draw(); ... } class Image extends Graphic{ public void load() { ... } public void draw() { ... } ... } class ImgProxy extends Graphic { public void load() {

if(image == null) { image = new Image(filename); } ... public void draw() { ... } ...

}

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. Where to use & benefits

One request should be handled by more than one object. Don't know which object should handle a request, probably more than one object will handle it automatically. Reduce coupling. Flexible in handling a request. Related patterns includeo

Composite, which a chain of responsibility pattern is often applied in conjunction with.

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 { protected final double base = 500; protected PurchasePower successor; public void setSuccessor(PurchasePower successor){ this.successor = successor; } abstract public void processRequest(PurchaseRequest request); } class ManagerPPower extends PurchasePower { private final double ALLOWABLE = 10 * base; public void processRequest(PurchaseRequest request ) { if( request.getAmount() < ALLOWABLE ) System.out.println("Manager will approve $"+ request.getAmount()); else if( successor != null) successor.processRequest(request);

} }

class DirectorPPower extends PurchasePower { private final double ALLOWABLE = 20 * base; public void processRequest(PurchaseRequest request ) { if( request.getAmount() < ALLOWABLE ) System.out.println("Director will approve $"+ request.getAmount()); else if( successor != null) successor.processRequest(request);

} }

class VicePresidentPPower extends PurchasePower { private final double ALLOWABLE = 40 * base; 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 PresidentPPower extends PurchasePower { private final double ALLOWABLE = 60 * base; public void processRequest(PurchaseRequest request){ if( request.getAmount() < ALLOWABLE ) System.out.println("President will approve $" + request.getAmount()); else System.out.println( "Your request for $" + request.getAmount() + " needs a board meeting!"); } } class PurchaseRequest { private int number; private double amount; private String purpose; public PurchaseRequest(int number, double amount, String purpose){ this.number = number; this.amount = amount; this.purpose = purpose; } public double getAmount() { return amount; } public void setAmount(double amt){ amount = amt; } public String getPurpose() { return purpose; } public void setPurpose(String reason) { purpose = reason; } public int getNumber(){ return number; } public void setNumber(int num) { number = num; } } 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); //enter ctrl+c to kill. try{ while (true) { System.out.println("Enter the amount to check who should approve your expenditure."); System.out.print(">"); double d = Double.parseDouble(new BufferedReader(new InputStreamReader(System.in)).readLine()); manager.processRequest(new PurchaseRequest(0, d, "General")); } }catch(Exception e){ System.exit(1); } } } C:\ Command Prompt

C:\> javac CheckAuthority.java C:\> java CheckAuthority Enter the amount to check who should approve your expenditure. >500 Manager will approve $500.0 Enter the amount to check who should approve your expenditure. >5000 Director will approve $5000.0 Enter the amount to check who should approve your expenditure. >11000 Vice President will approve $11000.0 Enter the amount to check who should approve your expenditure. >30000 Your request for $30000.0 needs a board meeting! Enter the amount to check who should approve your expenditure. >20000 President will approve $20000.0 Enter the amount to check who should approve your expenditure. > C:\> You may redo it using interface instead of abstract class. The composite pattern is often used with chain of responsibility. That means a class may contain the related class that may handle the request.

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. Where to use & benefits

One action can be represented in many ways, like drop-down menu, buttons and popup menu. Need a callback function, i.e., register it somewhere to be called later. Specify and execute the request at different time Need to undo an action by storing its states for later retrieving.

Decouple the object with its trigger Easily to be extensible by not touching the old structure. Related patterns includeo

Composite, which aggregates an object. You may combine it into a composite command pattern. In general, a composite command is an instance of the composite. Memento, which keeps state of an object. Command supports undo and redo.

o

Example The simple example of Command pattern is to design a Command interface and with an execute method like this: public interface Command { public void execute(); } 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. public interface EventLister { ... } public interface ActionListener extends EventListener { ... } public interface Action extends ActionListener { ... } There is an abstract class called AbstractAction which implements Action interface. It has the following design. public abstract class AbstractAction extends Object implements Action, Cloneable, Serializable 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.

class ExitAction extends AbstractAction { private Component target; public ExitAction(String name, Icon icon, Component t){ putValue(Action.NAME, name); putValue(Action.SMALL_ICON, icon); putValue(Action.SHORT_DESCRIPTION, name + " the program"); target = t; } public void actionPerformed(ActionEvent evt) { int answer = JOptionPane.showConfirmDialog(target, "Are you sure you want to exit? ", "Confirmation", JOptionPane.YES_NO_OPTION); if ( answer == JOptionPane.YES_OPTION) { System.exit(0); } } } Similar to the above exit action, the submit action is as follows: class SubmitAction extends AbstractAction { private Component target; public SubmitAction(String name, Icon icon, Component t){ putValue(Action.NAME, name); putValue(Action.SMALL_ICON, icon); putValue(Action.SHORT_DESCRIPTION, name + " the program"); target = t; } public void actionPerformed(ActionEvent evt) { JOptionPane.showMessageDialog(target, "submit action clicked "); } } 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.*; class ExitAction extends AbstractAction { private Component target; public ExitAction(String name, Icon icon, Component t){ putValue(Action.NAME, name); putValue(Action.SMALL_ICON, icon); putValue(Action.SHORT_DESCRIPTION, name + " the program"); target = t; } public void actionPerformed(ActionEvent evt) {

int answer = JOptionPane.showConfirmDialog(target, "Are you sure you want to exit? ", "Confirmation", JOptionPane.YES_NO_OPTION); if ( answer == JOptionPane.YES_OPTION) { System.exit(0); } } } class SubmitAction extends AbstractAction { private Component target; public SubmitAction(String name, Icon icon, Component t){ putValue(Action.NAME, name); putValue(Action.SMALL_ICON, icon); putValue(Action.SHORT_DESCRIPTION, name + " the program"); target = t; } public void actionPerformed(ActionEvent evt) { JOptionPane.showMessageDialog(target, "submit action clicked "); } } class Test extends JFrame{ Test() { Action ea = new ExitAction("Exit", null, this); Action sa = new SubmitAction("Submit", null, this); JMenuBar jbr = new JMenuBar(); JMenu dropmenu= new JMenu("File"); JMenuItem submitmenu = new JMenuItem(sa); JMenuItem exitmenu = new JMenuItem(ea); dropmenu.add(submitmenu); dropmenu.add(exitmenu); jbr.add(dropmenu); setJMenuBar(jbr); final JPopupMenu pop = new JPopupMenu("PopMenu"); pop.add(sa); pop.add(ea); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { showPopup(e); } public void mouseReleased(MouseEvent e) { showPopup(e); } 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); Container con = getContentPane(); con.add(jp, "South"); setTitle("Command pattern example"); setSize(400,200); setVisible(true); } public static void main(String[] args) { new Test(); }

} java Test

A windows pops up. 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.

Interpreter Definition Provides a definition of a macro language or syntax and parsing into objects in a program. Where to use & benefits

Need your own parser generator. Translate a specific expression. Handle a tree-related information. Related patterns includeo

Composite, which is an instance in an interpreter.

o o o

Flyweight, which shows how to share symbols with abstract context. Iterator, which is used to traverse the tree structure. 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; public Parser(String e, String t) { expression = e; token = t; } public void myParser() { StringTokenizer holder = new StringTokenizer(expression, token); String[] toBeMatched = new String[holder.countTokens()]; int idx = 0; while(holder.hasMoreTokens()) { String item = holder.nextToken(); int start = item.indexOf(","); if(start==0) { item = item.substring(2); } toBeMatched[idx] = item; idx ++; } result = Arrays.asList(toBeMatched); } public List getParseResult() { return result; } public void interpret() { StringBuffer buffer = new StringBuffer(); ListIterator list = result.listIterator(); while (list.hasNext()){ String token = (String)list.next(); if (token.equals("SFO")){ token = "San Francisco"; }else if(token.equals("CA")) { token = "Canada"; }

//... buffer.append(" " + token); } interpreted = buffer.toString(); } public String getInterpretedResult() { return interpreted; } public static void main(String[] args) { String source = "dest='SFO',origin='CA',day='MON'"; 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

Iterator Definition Provide a way to move through a list of collection or aggregated objects without knowing its internal representations. Where to use & benefits

Use a standard interface to represent data objects. Use s standard iterator built in each standard collection, like List, Sort, or Map. Need to distinguish variations in the traversal of an aggregate. Similar to Enumeration class, but more effective. Need to filter out some info from an aggregated collection. Related patterns includeo

Composite, which supports recursive structures, whereas an iterator is often applied on it. Factory Method, which provides appropriate instances needed by an iterator subclasses. Memento, which is often used with an Iterator. The iterator stores the memento internally.

o

o

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; } public String toString() { return "Piece worker: " + getName(); } } class HourlyWorker implements Employee { private double hourlyWage; private double hours; private String name; 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 0) salary = s; else salary = 0; } void setCommission(double c) { if ( c > 0) commission = c; else commission = 0; } void setTotalSales(double ts) { if (ts > 0 ) totalSales = ts; else totalSales = 0; } public String getName() { 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 list.add(new list.add(new list.add(new list.add(new

HourlyWorker("Babara", 13.75, 40)); Manager("Peter", 1200.00)); CommissionWorker("Margret", 600.0,5.5, 200.25)); PieceWorker("Mark", 4.5, 333)); HourlyWorker("William", 31.25, 50));

} } %java EmployeeTest Use built-in iterator: Manager: Bill earns $800.0 Commission worker:Newt earns $405.999625 Piece worker: Al earns $500.0 Hourly worker: Babara earns $550.0 Manager: Peter earns $1200.0 Commission worker:Margret earns $611.01375 Piece worker: Mark earns $1498.5 Hourly worker: William earns $1562.5

System.out.println("Use built-in iterator:"); Iterator iterator = list.iterator(); while(iterator.hasNext()) { Employee em = (Employee)iterator.next(); System.out.print(em + " earns $"); System.out.println(em.earnings()); }

The above example also shows a dynamic binding feature which is popular in ObjectOriented 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.

Mediator Definition Define an object that encapsulates details and other objects interact with such object. The relationships are loosely decoupled. Where to use & benefits

Partition a system into pieces or small objects. Centralize control to manipulate participating objects(a.k.a colleagues) Clarify the complex relationship by providing a board committee. Limit subclasses. Improve objects reusabilities. Simplify object protocols. The relationship between the control class and other participating classes is multidirectional. Related patterns includeo

Facade, which abstracts a subsystem to provide a more convenient interface, and its protocol is unidirectional, whereas a mediator enables cooperative behavior and its protocol is multidirectional. Command, which is used to coordinate functionality. Observer, which is used in mediator pattern to enhance communication.

o o

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(); } } class BtnSearch extends JButton implements Command { Mediator med; BtnSearch(ActionListener al, Mediator m) { super("Search"); addActionListener(al); med = m; med.registerSearch(this); } public void execute() { med.search(); } } class BtnBook extends JButton implements Command { Mediator med; BtnBook (ActionListener al, Mediator m) { super("Book"); addActionListener(al); med = m; med.registerBook(this);

} public void execute() { med.book(); } } 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. 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(); } } The following is a complete code for the above program. interface Command { void execute(); } class Mediator { BtnView btnView; BtnSearch btnSearch;

} 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(); } } class BtnSearch extends JButton implements Command { Mediator med; BtnSearch(ActionListener al, Mediator m) {

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..."); }

super("Search"); addActionListener(al); med = m; med.registerSearch(this); } public void execute() { med.search(); } } class BtnBook extends JButton implements Command { Mediator med; BtnBook (ActionListener al, Mediator m) { super("Book"); addActionListener(al); med = m; med.registerBook(this); } public void execute() { med.book(); } } 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) {

} } java MediatorDemo

new MediatorDemo();

A window will pop up. Try the features.

Memento Definition To record an object internal state without violating encapsulation and reclaim it later without knowledge of the original object. Where to use & benefits

Let some info in an object to be available by another object by using default access control. Save some info for later uses. Need undo/redo features. Used in database transaction. Related patterns includeo

Command, which supports undo or redo features, whereas a memento keeps state of an object. Iterator, which provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation, whereas a memento can be used for iteration.

o

Example To design a program with Memento feature is used to combine several design patterns like Command, Mediator or Iterator. Here is an example expanded from Mediator example. To show the Memento design concept, we record a dice number. This is very simple program. The Memento class just holds a number. 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. 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 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);

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); }

Finally, write a demo class. 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(); } } The complete workable program is as follows. Copy it, compile it and run it. import import import import import import javax.swing.*; java.awt.event.*; java.awt.FontMetrics; java.awt.*; java.util.*; 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) {

} } 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(); } }

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);

Observer Definition One object changes state, all of its dependents are updated automatically. Where to use & benefits

One change affects one or many objects. Many object behavior depends on one object state. Need broadcast communication. AKA Publish-Subscribe.

Maintain consistency between objects keep classes from becoming too tightly coupled, which would hamper reusability. Related patterns includeo

Singleton, which is used to make observable object unique and accessible globally. Mediator, which is used to encapsulate updated objects.

o

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.*; class DisplayForm extends JFrame { InputFormObserver input = new InputFormObserver(); InputForm inputForm ; Observable obsInput; JTextField display; //... public DisplayForm() { addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); }}); inputForm = new InputForm(); obsInput = inputForm.getInputInfo(); obsInput.addObserver(input); display = new JTextField(10); display.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); getContentPane().add(display); setTitle("Observer form"); setSize(200,100);

setLocation(200,100); setVisible(true); } private class InputFormObserver implements Observer { public void update(Observable ob, Object o) { doSomeUpdate(); if (obsInput.countObservers()>0) obsInput.deleteObservers(); obsInput = inputForm.getInputInfo(); obsInput.addObserver(input); } } 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; }

public String getText() { return input.getText(); } private class InformDisplay extends Observable { public void notifyObservers() { setChanged(); super.notifyObservers(); } public String getChange() { return input.getText(); } } //...

} java DisplayForm

Two windows will come up: one for user input, the other for observing user input. Enter data in the input window, a dialog box from other window shows up and the input data has been shown in the other window. State Definition An object's behavior chang