25
Abstract Factory Definition Provides one level of interface higher than the factory pattern. It is used to return one o f several factories. Where to use & benefits y Creates families of related or dependent o bjects like Kit. y Provides a class library of products, exposing interface not implementation. y  Needs to isolate concrete classes f rom their super classes. y A system needs independent of how its products are created, composed, and represented. y Try to enforce a constraint. y An alternative to Facade to hide platform-specifi c classes y Easily extensible to a system or a family y R elated patterns include o Factory method, which is often implemented with an a bstract factory. o Singleton, which is often implemented with an a bstract factory. o Prototype , which is o ften implemented with an abstract factory. o Facade, which is often used with an abstract factory by providing an interface for creating implementing class. Example Suppose you need to wri te a p rogram 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 foll owing wa y: classDataInfo {} interface Local { DataInfo[] loadDB(String filename); }

Deisgn Pattern

Embed Size (px)

Citation preview

Page 1: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 1/25

Abstract Factory

Definition

Provides one level of interface higher than the factory pattern. It is used to return one of severalfactories.

Where to use & benefits

y  Creates families of related or dependent objects like Kit.y  Provides a class library of products, exposing interface not implementation.

y   Needs to isolate concrete classes from their super classes.y  A

system needs independent of how its products are created, composed, and represented.y  Try to enforce a constraint.y  An alternative to Facade to hide platform-specific classes

y  Easily extensible to a system or a familyy  R elated patterns include

o  Factory method, which is often implemented with an abstract factory.o  Singleton, which is often implemented with an abstract factory.

o  Prototype, which is often implemented with an abstract factory.o  Facade, which is often used with an abstract factory by providing an interface for 

creating implementing class.

Example

Suppose you need to write a program to show data in two different places. Let's say from a localor 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 patternto design the interface in the following way:

classDataInfo {}

interface Local {

DataInfo[] loadDB(String filename);

}

Page 2: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 2/25

interface Remote extends Local{

void connect2WWW(String url);

}

classLocalMode implements Local {

publicDataInfo[] loadDB(String name) {

System.out.print("Load from a local database ");

return null;

}

}

classRemoteMode implements Remote {

public void connect2WWW(String url) {

System.out.println("Connect to a remote site ");

}

publicDataInfo[] loadDB(String name) {

System.out.println("Load from a remote database ");

return null;

}

}

// The Abstract Factory

interfaceConnectionFactory {

Local getLocalConnection();

Remote getRemoteConnection();

}

classDataManager implements ConnectionFactory {

boolean local = false;

DataInfo[] data;

//...

public Local getLocalConnection() {

return new LocalMode();

}

public Remote getRemoteConnection() {

return new RemoteMode();

}

public voidloadData() {

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 {

Page 3: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 3/25

public static void main(String[] args) {

DataManagerdm = 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

RemoteModerm = (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

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 alocation variable in.

Page 4: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 4/25

Builder

Definition

Construct a complex object from simple objects step by step.

Where to use & benefits

y  Make a complex object by specifying only its type and content. The built object is

shielded from the details of its construction.y  Want to decouple the process of building a complex object from the parts that make up

the object.y 

Isolate code for construction and representation.y  Give you finer control over the construction process.y  R elated patterns include

o  A bstract Factory, which focuses on the layer over the factory pattern (may besimple or complex), whereas a builder pattern focuses on building a complex

object from other simple objects.o  Composite, which is often used to build a complex object.

Example

To build a house, we will take several steps:

y   build foundation,

y   build frame,y   build exterior,

y   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 aWork Shop class to force the order of these 4 steps (that is to say thatwe 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.

importjava.util.*;

classWorkShop {

//force the order of building process

public void construct(HouseBuilderhb) {

hb.buildFoundation();

hb.buildFrame();

hb.buildExterior();

Page 5: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 5/25

hb.buildInterior();

}

}

//set steps for building a house

abstract class HouseBuilder {

protected House house = new House();

protected String showProgress() {

returnhouse.toString();

}

abstract public void buildFoundation();

abstract public void buildFrame();

abstract public void buildExterior();

abstract public void buildInterior();

}

classOneStoryHouse extends HouseBuilder {

publicOneStoryHouse(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()

//doBuiltinVacuum()

//doInsulation()

//doDryWall()

//doPainting()

//doLinoleum()

Page 6: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 6/25

//doCabinet()

//doTileWork()

//doLightFixtureBlinds()

//doCleaning()

//doInteriorInspection()

house.setProgress("Interior is under going");

}

}

classTwoStoryHouse extends HouseBuilder {

publicTwoStoryHouse(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");

}

}

Page 7: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 7/25

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

StringBufferff = 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 ");

}

returnff.toString();

}

}

classTestBuilder {

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

Page 8: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 8/25

 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

Page 9: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 9/25

Factory Method

Definition

Provides an abstraction or an interface and lets subclass or implementing classes decide whichclass or method should be instantiated or called, based on the conditions or parameters given.

Where to use & benefits

y  Connect parallel class hierarchies.y  A class wants its subclasses to specify the object.

y  A class cannot anticipate its subclasses, which must be created.y  A

family of objects needs to be separated by using shared interface.y  The code needs to deal with interface, not implemented classes.y  Hide concrete classes from the client.

y  Factory methods can be parameterized.y  The returned object may be either abstract or concrete object.

y  Providing hooks for subclasses is more flexible than creating objects directly.y  Follow naming conventions to help other developers to recognize the code structure.

y  R elated patterns includeo  A bstract Factory , which is a layer higher than a factory method.

o  Template method, which defines a skeleton of an algorithm to defer some steps tosubclasses or avoid subclasses

o Prototype, which creates a new object by copying an instance, so it reducessubclasses.

o  Singleton, which makes a returned factory method unique.

Examples

To illustrate such concept, let's use a simple example. To paint a picture, you may need severalsteps. 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;

Page 10: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 10/25

}

}

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.

Page 11: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 11/25

 

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 anobject to work on the local database. If the remote mode is set, you may instantiate an objectwhich may have more job to do like remote connection, downloading, etc.

interfaceDatabaseService {

publicDataInfogetDataInfo() throws Exception;

publicFieldInfogetFieldInfo() throws Exception;

public void write(FieldInfo fi) throws Exception;

public void modify(FieldInfo fi) throws Exception;

Page 12: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 12/25

public void delete(FieldInfo fi) throws Exception;

//...

}

class Data implements DatabaseService {

public Data(String fileName) {...};

public Data(URL url, String fileName) {....};

publicDataInfogetDataInfo() throws Exception {...};

publicFieldInfogetFieldInfo() throws Exception {...};

public void write(FieldInfo fi) throws Exception {...};

public void modify(FieldInfo fi) throws Exception {...};

public void delete(FieldInfo fi) throws Exception {...};

//....

}

classDataManager{

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.

R ecently, the company purchased a new machine which produces a binary data file, another newmachine 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 thespecified data format for the website.

Here comes a solution. Use an interface type to converge the different data file format. Thefollowing 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

classCSVFile implements Display{

Page 13: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 13/25

 

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

classXMLFile 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 fileclassDBFile 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

classTestFactory {

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 followsdisplay.load("");

display.formatConsistency();

}

}

//after compilation and run it

C:\>java TestFactory 1

load from a txt file

txt file format changed

Page 14: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 14/25

 

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

Page 15: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 15/25

Prototype

Definition

Cloning an object by reducing the cost of creation.

Where to use & benefits

y  When there are many subclasses that differ only in the kind of objects,

y  A system needs independent of how its objects are created, composed, and represented.y  Dynamic binding or loading a method.

y  Use one instance to finish job just by changing its state or parameters.y  A

dd and remove objects at runtime.y  S pecify new objects by changing its structure.y  Configure an application with classes dynamically.

y  R elated patterns includeo  A bstract Factory, which is often used together with prototype. An abstract factory

may store some prototypes for cloning and returning objects.o  Composite, which is often used with prototypes to make a part-whole

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

}

}

Page 16: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 16/25

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 hereif (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.

Page 17: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 17/25

The prototype is typically used to clone an object, i.e. to make a copy of an object. When anobject 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 implementCloneable interface and override the clone method(protected Object clone()).

class Complex implements Cloneable {

int[] nums = {1,2,3,4,5};

public Object clone() {

try {

returnsuper.clone();

}catch(CloneNotSupportedExceptioncnse) {

System.out.println(cnse.getMessage());

return null;

}

}

int[] getNums() {

returnnums;

}

}

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 Test12345

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 {

returnsuper.clone();

}catch(CloneNotSupportedExceptioncnse) {

System.out.println(cnse.getMessage());return null;

}

}

int[] getNums() {

returnnums;

}

}

class Test {

Complex c1 = new Complex();

Page 18: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 18/25

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 implementCloneable interface.

class Complex { 

int[] nums = {1,2,3,4,5};

public Complex clone() {

return new Complex();

int[] getNums() {

returnnums;

}

}

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;

Page 19: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 19/25

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 

Page 20: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 20/25

Singleton

Definition

One instance of a class or one value accessible globally in an application.

Where to use & benefits

y  Ensure unique instance by defining class final to prevent cloning.

y  May be extensible by the subclass by defining subclass final.y  Make a method or a variable public or/and static.

y  Access to the instance by the way you provided.y  W

ell control the instantiation of a class.y  Define one value shared by all instances by making it static.y  R elated patterns include

o  A bstract factory, which is often used to return unique objects.o  Builder , which is used to construct a complex object, whereas a singleton is used

to create a globally accessible object.o  Prototype, which is used to copy an object, or create an object from its prototype,

whereas a singleton is used to ensure that only one prototype is guaranteed.

Example

One file system, one window manager, one printer spooler, one Test engine, one Input/Outputsocket 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 RemoteConnectionrc = new RemoteConnection(connection);

privateRemoteConnection(Connect c) {

con = c;

....

}

public static RemoteConnectiongetRemoteConnection() {

returnrc;

}

public void setConnection(Connect c) {

this(c);

Page 21: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 21/25

}

}

usage:

RemoteConnectionrconn = 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 booleanhaveOne = 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();

}

voiddoSomething() {}

//...

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 Connectionsecond: You cannot have a second instance

For example to use a public static variable to ensure a unique.

class Employee {

public static final intcompanyID = 12345;

public String address;

Page 22: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 22/25

//...

}

classHourlyEmployee extends Employee {

public double hourlyRate;

//....

}

classSalaryEmployee extends Employee {

public double salary;

//...

}

class Test {

public static void main(String[] args) {

Employee Evens = new Employee();

HourlyEmployeeHellen = 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.

Page 23: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 23/25

Q9. What is Intercepting Filter pattern? 

Ans. Provides a solution for pre-processing and post-processing a request. It allows us todeclaratively apply filters for intercepting requests and responses. For ex. Servlet filters. 

Q10. What is Front Controller pattern? 

Ans. It manages and handles requests through a centralized code. This could either be through aservlet or a JSP (through a Java Bean). This Controller takes over the common processing which

happens on the presentation tier. The front controller manages content retrieval, security, viewmanagement and retrieval. 

Q11. What is View Helper pattern? 

Ans. There generally are two parts to any application ± the presentation and the business logics.

The ³View´ is responsible for the output-view formatting whereas ³Helper´ component is

responsible for the business logic. Helper components do content retrieval, validation andadaptation. Helper components generally use Business delegate pattern to access businessclasses. 

Q12. What is Composite View pattern? 

Ans. This pattern is used for creating aggregate presentations (views) from atomic sub-components. This architecture enables says piecing together of elementary view components

which makes the presentation flexible by allowing personalization and customization. 

Q13. What is Service to Worker pattern? 

Ans. This is used in larger applications wherein one class is used to process the requests while

the other is used to process the view part. This differentiation is done for maintainability. 

Q14. What is Dispatcher View pattern? 

Ans. This is similar to Service toWorker pattern except that it is used for smaller applications. Inthis one class is used for both request and view processing. 

Q15. What is Business Delegate pattern? 

Ans. T

his pattern is used to reduce the coupling between the presentation and business-logic tier.It provides a proxy to the façade from where one could call the business classes or DAO class.

This pattern can be used with Service Locator pattern for improving performance. 

Q16. What is Value Object (VO) pattern? 

Ans. Value Object is a serializable object which would contain lot of atomic values. These are

normal java classes which may have different constructors (to fill in the value of different data)

Page 24: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 24/25

and getter methods to get access to these data. VOs are used as a course grained call which gets

lots of data in one go (this reduces remote overhead). The VO is made serializable for it to be

transferred between different tiers within a single remote method invocation.

What is Session Façade pattern? 

Ans. This pattern hides the complexity of business components and centralizes the workflow. It provides course-grained interfaces to the clients which reduces the remote method overhead.

This pattern fits well with declarative transactions and security management. 

Q18. What is Value Object Assembler pattern? 

Ans. This pattern allows for composing a Value Object from different sources which could be

EJBs, DAOs or Java objects. 

Q19. What is Value List Handler pattern? 

Ans. This pattern provides a sound solution for query execution and results processing. 

Q20. What is Service Locator pattern? 

Ans. It provides a solution for looking-up, creating and locating services and encapsulating their complexity. It provides a single point of control and it also improves performance. 

Q21. What is Data Access Object pattern? 

Ans. It provides a flexible and transparent access to the data, abstracts the data sources and hides

the complexity of Data persistence layer. This pattern provides for loose coupling between business and data persistence layer. 

Q22. What is EJB Command pattern? 

Ans. Session Façade and EJB Command patterns are competitor patterns. It wraps business logicin command beans, decouples the client and business logic tier, and reduces the number of 

remote method invocations. 

Q23. What is Version Number pattern? 

Ans. This pattern is used for transaction and persistence and provides a solution for maintainingconsistency and protects against concurrency. Every time a data is fetched from the database, itcomes out with a version number which is saved in the database. Once any update is requested

on the same row of the database, this version is checked. If the version is same, the update isallowed else not. 

Q24. What all patterns are used to improve performance and scalability of the application?  

Page 25: Deisgn Pattern

8/8/2019 Deisgn Pattern

http://slidepdf.com/reader/full/deisgn-pattern 25/25

Ans. VO, Session Façade, Business Delegate and Service Locator. 

Q25. What design patterns could be used to manage security? 

Ans. Single Access Point, Check point and R ole patterns.