You are on page 1of 17

DESIGNPATTRENS

RavikumarMaddi
• Designpatterns
aredocumentedtriedandtestedsolutionsforrecurri
ngproblemsinagivencontext.Sobasicallyyouhavea
problemcontextandtheproposedsolutionforthesa
me.Designpatternsexistedinsomeorotherformrigh
tfromtheinceptionstageofsoftwaredevelopment.L
et'ssayifyouwanttoimplementasortingalgorithmth
efirstthingcomestomindisbubblesort.Sotheproble
missortingandsolutionisbubblesort.Sameholdstru
efordesignpatterns.
• Creational Patterns • Behavioral Patterns
• Abstract Factory:- Creates an instance of several families of classes • Mediator:-Defines simplified communication
• Builder: - Separates object construction from its representation. Ex: between classes.
simple- constructor overloading simple example. AWT Container
components are the best example for Builder factory. It is nothing but • Memento:-Capture and restore an object's
creating of object in different ways based on the situations. internal state.
• Factory Method:- Creates an instance of several derived classes • Interpreter:- A way to include language elements
• Prototype:- A fully initialized instance to be copied or cloned in a program.
• Singleton:- A class in which only a single instance can exist • Iterator:-Sequentially access the elements of a
collection.
Note: - The best way to remember Creational pattern is by remembering • Chain of Resp: - A way of passing a request
ABFPS (Abraham Became First President of States). between a chain of objects.
• Command:-Encapsulate a command request as an
• Structural Patterns object. ActionServlet
• Adapter:-Match interfaces of different classes . • State:-Alter an object's behavior when its state
• Bridge:-Separates an objects abstraction from its implementation. It changes.
is mainly we use mapping between server objects and client objects-
regarding extract needed information, changing regarding client view • Strategy:-Encapsulates an algorithm inside a
formatting. class.
• Composite:-A tree structure of simple and composite objects. • Observer: - A way of notifying change to a
• Decorator:-Add responsibilities to objects dynamically. Wrapper number of classes.
classes are simple example for decorator pattren
• Facade:-A single class that represents an entire subsystem. • Template Method:-Defer the exact steps of an
algorithm to a subclass.
• Flyweight:-A fine-grained instance used for efficient sharing.
• Proxy:-An object representing another object. Ex: RMI • Visitor:-Defines a new operation to a class without
change.

Note : To remember structural pattern best is (ABCDFFP)


TherearethreebasicclassificationsofpatternsCreational,Structural,andBehavioralpatterns.
• CreationalPatterns
– AbstractFactory:-Createsaninstanceofseveralfamiliesofclasses
– Builder:-Separatesobjectconstructionfromitsrepresentation
– FactoryMethod:-Createsaninstanceofseveralderivedclasses
FactoryMethod:-Createsaninstanceofseveralderivedclasses
– Prototype:-Afullyinitializedinstancetobecopiedorcloned
Prototype:-Afullyinitializedinstancetobecopiedorcloned
– Singleton:-Aclassinwhichonlyasingleinstancecanexist
Note:-
ThebestwaytorememberCreationalpatternisbyrememberingABFPS(AbrahamBecameFirstPreside
ntofStates).

• StructuralPatterns
– Adapter:-Matchinterfacesofdifferentclasses.
Adapter:-Matchinterfacesofdifferentclasses.
– Bridge:-Separatesanobject'sabstractionfromitsimplementation.
Bridge:-Separatesanobject'sabstractionfromitsimplementation.
– Composite:-Atreestructureofsimpleandcompositeobjects.
– Decorator:-Addresponsibilitiestoobjectsdynamically.
– Façade:-Asingleclassthatrepresentsanentiresubsystem.
Façade:-Asingleclassthatrepresentsanentiresubsystem.
– Flyweight:-Afine-grainedinstanceusedforefficientsharing.
Flyweight:-Afine-grainedinstanceusedforefficientsharing.
– Proxy:-Anobjectrepresentinganotherobject.
Note:Torememberstructuralpatternbestis(ABCDFFP)

• BehavioralPatterns
– Mediator:-Definessimplifiedcommunicationbetweenclasses.
Mediator:-Definessimplifiedcommunicationbetweenclasses.
– Memento:-Captureandrestoreanobject'sinternalstate.
– Interpreter:-Awaytoincludelanguageelementsinaprogram.
– Iterator:-Sequentiallyaccesstheelementsofacollection.
Iterator:-Sequentiallyaccesstheelementsofacollection.
– ChainofResp:-Awayofpassingarequestbetweenachainofobjects.
ChainofResp:-Awayofpassingarequestbetweenachainofobjects.
– Command:-Encapsulateacommandrequestasanobject.
– State:-Alteranobject'sbehaviorwhenitsstatechanges.
State:-Alteranobject'sbehaviorwhenitsstatechanges.
– Strategy:-Encapsulatesanalgorithminsideaclass.
Strategy:-Encapsulatesanalgorithminsideaclass.
– Observer:-Awayofnotifyingchangetoanumberofclasses.
– TemplateMethod:-Defertheexactstepsofanalgorithmtoasubclass.
– Visitor:-Definesanewoperationtoaclasswithoutchange.
Visitor:-Definesanewoperationtoaclasswithoutchange.
Thread-safe Singleton
package com.designpatterns;

public class ThreadSafeSingleton {

/* Here is the instance of the Singleton */


private static ThreadSafeSingleton instance_;

/* Need the following object to synchronize */


/* a block */
private static Object syncObject_;

/* Prevent direct access to the constructor */


private ThreadSafeSingleton() {
super();
super();
}

public static ThreadSafeSingleton getInstance() {

/* in a non-thread-safe version of a Singleton */


/* the following line could be executed, and the */
/* thread could be immediately swapped out */
if (instance_ == null)
null) {

synchronized (syncObject_) {

if (instance_ == null)
null) {
instance_ = new ThreadSafeSingleton();
}

}
return instance_;
}
}
• What major patterns do the Java APIs utilize?
Design patterns are used and supported extensively throughout the Java APIs.
Here are some examples:
– The Model-View-Controller design pattern is used extensively throughout the
Swing API.
– The getInstance() method in java.util.Calendar is an example of a simple form of
the Factory Method design pattern.
– The classes java.lang.System and java.sql.DriverManager are examples of the
Singleton pattern, although they are not implemented using the approach
recommended in the GoF book but with static methods.
– The Prototype pattern is supported in Java through the clone() method defined
in class Object and the use of java.lang.Cloneable interface to grant permission
for cloning.
– The Java Swing classes support the Command pattern by providing an Action
interface and an AbstractAction class.
– The Java 1.1 event model is based on the observer pattern. In addition, the
interface java.util.Observable and the class java.util.Observer provide support for
this pattern.
– The Adapter pattern is used extensively by the adapter classes in java.awt.event.
– The Proxy pattern is used extensively in the implementation of Java's Remote
Method Invocation (RMI) and Interface Definition Language (IDL) features.
– The structure of Component and Container classes in java.awt provide a good
example of the Composite pattern.
– The Bridge pattern can be found in the separation of the components in java.awt
(e.g., Button and List), and their counterparts in java.awt.peer.
Which patterns were used by Sun in designing the Enterprise JavaBeans
model?
Many design patterns were used in EJB, and some of them are clearly identifiable by their naming
convention. Here are several:
1. Factory Method: Define a interface for creating classes, let a subclass (or a helper class) decide
which class to instantiate.
This is used in EJB creation model. EJBHome defines an interface for creating the EJBObject
implementations. They are actually created by a generated container class. See
InitialContextFactory interface that returns an InitialContext based on a properties hashtable.
2.Singleton: Ensure a class has only one instance, and provide a global point of access to it.
There are many such classes. One example is javax.naming.NamingManager
3. Abstract Factory: Provide an interface for creating families of relegated or dependent objects
without specifying their concrete classes. We have interfaces called InitialContext,
InitialContextFactory. InitialContextFactory has methods to get InitialContext.
4.Builder: Separate the construction of a complex factory from its representation so that the same
construction process can create different representations. InitialContextFactoryBuilder can create
a InitialContextFactory.
5. Adapter: Convert the interface of a class into another interface clients expect. In the EJB
implementation model, we implement an EJB in a class that extends SessionBean or a
EntityBean. We don't directly implement the EJBObject/home interfaces. EJB container generates
a class that adapts the EJBObject interface by forwarding the calls to the enterprise bean class
and provides declarative transaction, persistence support.
6. Proxy: Provide a surrogate for other object to control access to it. We have remote RMI-CORBA
proxies for the EJB's.
7. Memento: Without violating encapsulation, capture and externalize an object's internal state so
that the object can be restored to this state later. Certainly this pattern is used in
activating/passivating the enterprise beans by the container/server.

You might also like