You are on page 1of 18

Design Pattern in java Notes

object creation pattern --- singleton,factory,abstract factory,builder

Structural design pattern -- proxy,decorator,observer

behavioral design pattern -- iterator,command.

http://www.javagyan.com/tutorials/corej2eepatterns

http://www.java67.com/2012/09/top-10-java-design-pattern-interview-question-answer.html

http://javarevisited.blogspot.com/2011/12/observer-design-pattern-java-example.html

Intercepting Filter intercepts incoming requests and outgoing responses and applies a filter. These filters
may be added and removed in a declarative manner, allowing them to be applied unobtrusively in a
variety of combinations. After this preprocessing and/or post-processing is complete, the final filter in
the group vectors control to the original target object. For an incoming request, this is often a Front
Controller, but may be a View.

Front Controller is a container to hold the common processing logic that occurs within the
presentation tier and that may otherwise be erroneously placed in a View. A controller handles requests
and manages content retrieval, security, view management, and navigation, delegating to a Dispatcher
component to dispatch to a View.

Application Controller centralizes control, retrieval, and invocation of view and command processing.
While a Front Controller acts as a centralized access point and controller for incoming requests, the
Application Controller is responsible for identifying and invoking commands, and for identifying and
dispatching to views.

Context Object encapsulates state in a protocol-independent way to be shared throughout your


application. Using Context Object makes testing easier, facilitating a more generic test environment with
reduced dependence upon a specific container.

View Helper encourages the separation of formatting-related code from other business logic. It
suggests using Helper components to encapsulate logic relating to initiating content retrieval, validation,
and adapting and formatting the model. The View component is then left to encapsulate the
presentation formatting. Helper components typically delegate to the business services via a Business
Delegate or an Application Service, while a View may be composed of multiple subcomponents to create
its template.

Composite View suggests composing a View from numerous atomic pieces. Multiple smaller views,
both static and dynamic, are pieced together to create a single template. The Service to Worker and
Dispatcher View patterns represent a common combination of other patterns from the catalog. The two
patterns share a common structure, consisting of a controller working with a Dispatcher, Views, and
Helpers. Service to Worker and Dispatcher View have similar participant roles, but differ in the division of
labor among those roles. Unlike Service to Worker, Dispatcher View defers business processing until view
processing has been performed.

Service to worker performs core request handling and invoke business logic before control is passed to
the view. It centralizes control and request handling to retrieve a presentation model before turning
control over to the view. The view generates a dynamic response based on the presentation model.

Dispatcher View combines a controller and dispatcher with views and helpers to handle client requests
and prepare a dynamic presentation as the response. Controllers do not delegate content retrieval to
helpers, because these activities are deferred to the time of view processing. A dispatcher is responsible
for view management and navigation and can be encapsulated either within a controller, a view, or a
separate component.

Business Tier Patterns

Business Delegate reduces coupling between remote tiers and provides an entry point for accessing
remote services in the business tier. A Business Delegate might also cache data as necessary to improve
performance. A Business Delegate encapsulates a Session Façade and maintains a one-to-one
relationship with that Session Façade. An Application Service uses a Business Delegate to invoke a
Session Façade.

Service Locator encapsulates the implementation mechanisms for looking up business service
components. A Business Delegate uses a Service Locator to connect to a Session Façade. Other clients
that need to locate and connect to Session Façade, other business-tier services, and web services can
use a Service Locator.

Session Façade provides coarse-grained services to the clients by hiding the complexities of the
business service interactions. A Session Façade might invoke several Application Service implementations
or Business Objects. A Session Façade can also encapsulate a Value List Handler.
Application Service centralizes and aggregates behavior to provide a uniform service layer to the
business tier services. An Application Service might interact with other services or Business Objects. An
Application Service can invoke other Application Services and thus create a layer of services in your
application.

Business Object implements your conceptual domain model using an object model. Business Objects
separate business data and logic into a separate layer in your application. Business Objects typically
represent persistent objects and can be transparently persisted using Domain Store.

Composite Entity implements a Business Object using local entity beans and POJOs. When
implemented with bean-managed persistence, a Composite Entity uses Data Access Objects to facilitate
persistence.

The Transfer Object pattern provides the best techniques and strategies to exchange data across tiers
(that is, across system boundaries) to reduce the network overhead by minimizing the number of calls to
get data from another tier.

The Transfer Object Assembler constructs a composite Transfer Object from various sources. These
sources could be EJB components, Data Access Objects, or other arbitrary Java objects. This pattern is
most useful when the client needs to obtain data for the application model or part of the model.

The Value List Handler uses the GoF iterator pattern to provide query execution and processing
services. The Value List Handler caches the results of the query execution and return subsets of the
result to the clients as requested. By using this pattern, it is possible to avoid overheads associated with
finding large numbers of entity beans. The Value List Handler uses a Data Access Object to execute a
query and fetch the results from a persistent store.

Integration Tier Patterns

Data Access Object enables loose coupling between the business and resource tiers. Data Access
Object encapsulates all the data access logic to create, retrieve, delete, and update data from a
persistent store. Data Access Object uses Transfer Object to send and receive data.
Service Activator enables asynchronous processing in your enterprise applications using JMS. A Service
Activator can invoke Application Service, Session Façade or Business Objects. You can also use several
Service Activators to provide parallel asynchronous processing for long running tasks.

Domain Store provides a powerful mechanism to implement transparent persistence for your object
model. It combines and links several other patterns including Data Access Objects.

Web Service Broker exposes and brokers one or more services in your application to external clients as
a web service using XML and standard web protocols. A Web Service Broker can interact with Application
Service and Session Façade. A Web Service Broker uses one or more Service Activators to perform
asynchronous processing of a request.

J2EE Design Patterns

These design patterns are specifically concerned with the presentation tier. These patterns are identified
by Sun Java Center.

J2EE DESIGN PATTERNS: MVC DESIGN PATTERN,

Creational Design Patterns

Creational design patterns are concerned with the way of creating objects. These design patterns are
used when a decision must be made at the time of instantiation of a class (i.e. creating an object of a
class).

Singleton

Factory

Abstract Factory

Builder

Prototype

Behavioral Design Patterns

Behavioral design patterns are concerned with the interaction and responsibility of objects.

In these design patterns, the interaction between the objects should be in such a way that they can
easily talk to each other and still should be loosely coupled.

That means the implementation and the client should be loosely coupled in order to avoid hard coding
and dependencies.
Template Method

Mediator

Chain of Responsibility

Observer

Strategy

Command

State

Visitor

Interpreter

Iterator

Structural design patterns are concerned with how classes and objects can be composed, to form larger
structures.

The structural design patterns simplifies the structure by identifying the relationships.

These patterns focus on, how the classes inherit from each other and how they are composed from
other classes.

Adapter

Composite

Proxy

Flyweight

Facade

Bridge

Decorator

Singleton Design pattern in java


Singleton classes are those, which has only one instance during application life cycle like
java.lang.Runtime.

Singleton is a class which has only one instance in whole application and provides a getInstance()
method to access the singleton instance.

There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime
which provides getRuntime() method to get access of it

and used to get free memory and total memory in Java. Classes implementing Thread Pools, database
Connection pools, caches,

loggers etc are generally made Singleton so as to prevent any class from accidently creating multiple
instances of such resource consuming classes.

Any class which you want to be available to whole application and whole only one instance is viable is
candidate of becoming Singleton. One example of this is Runtime class ,

since on whole java application only one runtime environment can be possible making Runtime
Singleton is right decision. Another example is a utility classes

Difference b.w static and Singleton pattern?

Static class provides better performance than Singleton pattern, because static methods are bonded on
compile time.

Singleton classes can be lazy loaded if its an heavy object, but static class doesn't have such advantages
and always eagerly loaded.

One more difference between Singleton and static is, ability to override. Since static methods in Java
cannot be overridden, they leads to inflexibility. On the other hand, you can override methods defined in
Singleton class by extending it.

Static classes are hard to mock and consequently hard to test than Singletons, which are pretty easy to
mock and thus easy to test. It’s easier to write JUnit test for Singleton than static classes, because you
can pass mock object whenever Singleton is expected, e.g. into constructor or as method arguments.

If your requirements needs to maintain state than Singleton pattern is better choice than static class,
because maintaining state in later case is nightmare and leads to subtle bugs.

What is Eager initilization in Singleton design pattern?

Eager initilization happens when we eagerly initialize the private static variable to hold the single
instance of the class at the time of its declaration.
public class SingletonMain {

private static SingletonMain singleton = new SingletonMain();

private SingletonMain(){

public static synchronized SingletonMain getInstance(){

return singleton;

@Override

protected Object clone() throws CloneNotSupportedException {

// TODO Auto-generated method stub

/*

* Here forcibly throws the exception for preventing to be cloned

*/

System.out.println("Trying to clone!!!!!!!!!!!1");

throw new CloneNotSupportedException();

// return super.clone();

public static void main(String args[]){

SingletonMain singleone = SingletonMain.getInstance();

try{

singleone.clone();

catch(Exception e){
e.printStackTrace();

What is lazy initilization in Singleton design pattern?

Due to the lazy instantiation, that is, the fact the object is not created until it is first needed(Used in
Hibernate)

Lazy initialization happens when the initialization of the Singleton class instance is delayed till its static
getInstance() is called by any client program.

And initialization of the Singleton class takes place inside the getInstance() method.

package com.singleton;

public class SingletonMain {

private static SingletonMain singletonInstance;

private SingletonMain(){

public static synchronized SingletonMain getInstance(){

if(singletonInstance == null){

singletonInstance = new SingletonMain();

return singletonInstance;

@Override

protected Object clone() throws CloneNotSupportedException {


// TODO Auto-generated method stub

/*

* Here forcibly throws the exception for preventing to be cloned

*/

System.out.println("Trying to clone!!!!!!!!!!!");

throw new CloneNotSupportedException();

// return super.clone();

public static void main(String args[]){

SingletonMain singleone = SingletonMain.getInstance();

SingletonMain singletwo = SingletonMain.getInstance();

try{

singleone.clone();

catch(Exception e){

e.printStackTrace();

}
SHALLOW CLONING AND DEEP CLONING IN DETAIL...

http://www.jusfortechies.com/java/core-java/deepcopy_and_shallowcopy.php

http://howtodoinjava.com/core-java/cloning/a-guide-to-object-cloning-in-java/
--- cloning in detail

http://www.java67.com/2013/05/difference-between-deep-copy-vs-shallow-
cloning-java.html --- best guide of all...

Difference between Deep and Shallow Copy in Java Object Cloning

Shallow copy and deep copy is related with cloning process so before go into the
deep of shallow and deep copy we need to understand what is clone in java.
Clone is nothing but the process of copying one object to produce the exact
object, which is not guaranteed. We all know in Java object is referred by
reference we can not copy one object directly to another object. So we have
cloning process to achieve this objective.

So we can define Cloning as “create a copy of object “ .I think now we are


somehow clear about the cloning but there is more to it depending on how we
are doing this copy, we can divide cloning into two types.

Shallow Copy

Deep Copy

Before going into the deep of shallow and deep copy we need to understand how
we achieve cloning in java.
In Java, everything is achieved through class, object and interface .

By default no Java class support cloning but Java provide one interface called
Cloneable,

which is a marker interface and by implementing this interface we can make the
duplicate copy of our object by calling clone() method of java.lang.Object class.

This Method is protected inside the object class and Cloneable interface is a
marker interface and this method also throw CloneNotSupportedException

if we have not implemented this interface and try to call clone() method of
Object class.

By default any clone() method gives the shallow copy of the object i.e.

if we invoke super.clone() then it’s a shallow copy but if we want to deep copy
we have to override the clone() method

and make it public and give own definition of making copy of object.

Now we let’s see what is shallow and deep copy of object in Java programming
language.

Shallow Copy

Whenever we use default implementation of clone method we get shallow copy of


object means it create new instance and copy all the field of object to that new
instance and return it as object type we need to explicitly cast it back to our original
object. This is shallow copy of the object. clone() method of the object class support
shallow copy of the object. If the object contains primitive as well as non primitive or
reference type variable In shallow copy, the cloned object also refers to the same
object to which the original object refers as only the object references gets copied and
not the referred objects themselves. That's why the name shallow copy or shallow
cloning in Java. If only primitive type fields or Immutable objects are there then there
is no difference between shallow and deep copy in Java.
Deep Copy

Whenever we need own meaning of copy not to use default implementation we call it
as deep copy, whenever we need deep copy of the object we need to implement
according to our need. So for deep copy we need to ensure all the member class also
implement the Cloneable interface and override the clone() method of the object
class. After that we override the clone() method in all those classes even in the classes
where we have only primitive type members otherwise we would not be able to call
the protected clone() method of Object class on the instances of those classes inside
some other class. It’s typical restriction of the protected access.

Regarding Passing of null values as arguments to methods (overloaded methods)

Decorator Design Pattern in java

Decorator design pattern is used to modify the functionality of an object at runtime.

Component Interface: The interface defining the methods that will be implemented. (Shape)
Component Implementation: The basic implementation of the component interface (Circle, Rectangle)

Abstract Decorators: abstract Decorator class implements the component interface and it has a HAS-A
relationship with the component interface. (ShapeDecorator)

Concrete Decorator – Decorator class implements the component interface and it has a HAS-A
relationship with the component interface.( RedShapeDecorator)

package com.decorator;

public interface Shape {

void draw();

package com.decorator;

public class Circle implements Shape {

@Override

public void draw() {

System.out.println("Shape: Circle");

package com.decorator;

public class Rectangle implements Shape {

@Override
public void draw() {

System.out.println("Shape: Rectangle");

package com.decorator;

public abstract class ShapeDecorator implements Shape {

protected Shape decoratedShape;

public ShapeDecorator(Shape decoratedShape){

this.decoratedShape = decoratedShape;

public void draw(){

package com.decorator;

public class RedShapeDecorator extends ShapeDecorator {

public RedShapeDecorator(Shape decoratedShape) {

super(decoratedShape);

@Override

public void draw() {


decoratedShape.draw();

setRedBorder(decoratedShape);

private void setRedBorder(Shape decoratedShape){

System.out.println("Border Color: Red");

package com.decorator;

public class ShapeDecoratorMain {

public static void main(String[] args) {

Shape circle = new Circle();

Shape redCircle = new RedShapeDecorator(new Circle());

Shape redRectangle = new RedShapeDecorator(new Rectangle());

circle.draw();

redCircle.draw();

redRectangle.draw();

//
Shape: Circle

Shape: Circle

Border Color: Red // modify the functionality of an object at runtime.

Shape: Rectangle

Border Color: Red // modify the functionality of an object at runtime.

Proxy Design Pattern…

In proxy pattern, a class controls the access of another class (Orginal class)

RMI API uses proxy design pattern. Stub and Skeleton are two proxy objects used in RMI.

We are going to create an Image interface and concrete classes implementing the Image interface.
ProxyImage is a a proxy class to reduce memory footprint of RealImage object loading

public interface Image {

void display();

public class RealImage implements Image {

private String fileName;

public RealImage(String fileName){

this.fileName = fileName;
loadFromDisk(fileName);//In the RealImage constructor call LoadFromDisk class…

@Override

public void display() {

System.out.println("Displaying " + fileName);

//ONLY FIRST TIME IMAGE WILL BE LOADED FROM HARDDISK

private void loadFromDisk(String fileName){

System.out.println("Loading " + fileName);

public class ProxyImage implements Image{

private RealImage realImage;

private String fileName;

public ProxyImage(String fileName){

this.fileName = fileName;

@Override

public void display() {

if(realImage == null)

realImage = new RealImage(17ilename); // will create the realImage object in proxy image //display
method …

realImage.display();//calling the realImage.display() from ProxyImage class

}
}

public class ProxyPatternDemo {

public static void main(String[] args) {

Image image = new ProxyImage("test_10mb.jpg");// realImage object is created thru ProxyImage


object for the first time and in the realImage Constructor the actual logic of loadingfromDisk is done

//image will be loaded from disk

image.display();

System.out.println("");

//image will not be loaded from disk

image.display();

You might also like