Design Pattern Quick Guide
Design Pattern Quick Guide
Design Pattern Quick Guide
Advertisements
Previous Page Next Page
Design patterns represent the best practices used by experienced objectoriented
software developers. Design patterns are solutions to general problems that
software developers faced during software development. These solutions were
obtained by trial and error by numerous software developers over quite a
substantial period of time.
What is Gang of Four (GOF)?
In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson und John
Vlissides published a book titled Design Patterns Elements of Reusable
ObjectOriented Software which initiated the concept of Design Pattern in
Software development.
These authors are collectively known as Gang of Four (GOF). According to these
authors design patterns are primarily based on the following principles of object
orientated design.
Program to an interface not an implementation
Favor object composition over inheritance
Usage of Design Pattern
Design Patterns have two main usages in software development.
Common platform for developers
Design patterns provide a standard terminology and are specific to particular
scenario. For example, a singleton design pattern signifies use of single object so
[Link] 1/110
10/14/2015 Design Pattern Quick Guide
all developers familiar with single design pattern will make use of single object and
they can tell each other that program is following a singleton pattern.
Best Practices
Design patterns have been evolved over a long period of time and they provide
best solutions to certain problems faced during software development. Learning
these patterns helps unexperienced developers to learn software design in an easy
and faster way.
Types of Design Pattern
As per the design pattern reference book Design Patterns Elements of
Reusable ObjectOriented Software , there are 23 design patterns. These
patterns can be classified in three categories: Creational, Structural and behavioral
patterns. We'll also discuss another category of design patterns: J2EE design
patterns.
S.N. Pattern & Description
Creational Patterns
These design patterns provides way to create objects while hiding the creation
1 logic, rather than instantiating objects directly using new opreator. This gives
program more flexibility in deciding which objects need to be created for a given
use case.
Structural Patterns
These design patterns concern class and object composition. Concept of
2
inheritance is used to compose interfaces and define ways to compose objects to
obtain new functionalities.
Behavioral Patterns
3 These design patterns are specifically concerned with communication between
objects.
J2EE Patterns
4 These design patterns are specifically concerned with the presentation tier. These
patterns are identified by Sun Java Center.
Factory Pattern
Factory pattern is one of most used design pattern in Java. This type of design
pattern comes under creational pattern as this pattern provides one of the best
ways to create an object.
In Factory pattern, we create object without exposing the creation logic to the
[Link] 2/110
10/14/2015 Design Pattern Quick Guide
client and refer to newly created object using a common interface.
Implementation
We're going to create a Shape interface and concrete classes implementing the
Shape interface. A factory class ShapeFactory is defined as a next step.
FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object.
It will pass information (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get
the type of object it needs.
Step 1
Create an interface.
[Link]
public interface Shape {
void draw();
}
Step 2
Create concrete classes implementing the same interface.
[Link]
public class Rectangle implements Shape {
@Override
public void draw() {
[Link] 3/110
10/14/2015 Design Pattern Quick Guide
[Link]("Inside Rectangle::draw() method.");
}
}
[Link]
public class Square implements Shape {
@Override
public void draw() {
[Link]("Inside Square::draw() method.");
}
}
[Link]
public class Circle implements Shape {
@Override
public void draw() {
[Link]("Inside Circle::draw() method.");
}
}
Step 3
Create a Factory to generate object of concrete class based on given information.
[Link]
public class ShapeFactory {
//use getShape method to get object of type shape
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if([Link]("CIRCLE")){
return new Circle();
} else if([Link]("RECTANGLE")){
return new Rectangle();
} else if([Link]("SQUARE")){
return new Square();
}
return null;
}
}
Step 4
Use the Factory to get object of concrete class by passing an information such as
type.
[Link]
[Link] 4/110
10/14/2015 Design Pattern Quick Guide
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//get an object of Circle and call its draw method.
Shape shape1 = [Link]("CIRCLE");
//call draw method of Circle
[Link]();
//get an object of Rectangle and call its draw method.
Shape shape2 = [Link]("RECTANGLE");
//call draw method of Rectangle
[Link]();
//get an object of Square and call its draw method.
Shape shape3 = [Link]("SQUARE");
//call draw method of circle
[Link]();
}
}
Step 5
Verify the output.
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.
Abstract Factory Pattern
Abstract Factory patterns works around a superfactory which creates other
factories. This factory is also called as Factory of factories. This type of design
pattern comes under creational pattern as this pattern provides one of the best
ways to create an object.
In Abstract Factory pattern an interface is responsible for creating a factory of
related objects, without explicitly specifying their classes. Each generated factory
can give the objects as per the Factory pattern.
Implementation
We're going to create a Shape and Color interfaces and concrete classes
implementing these interfaces. We creates an abstract factory class
AbstractFactory as next step. Factory classes ShapeFactory and ColorFactory are
defined where each factory extends AbstractFactory. A factory creator/generator
[Link] 5/110
10/14/2015 Design Pattern Quick Guide
class FactoryProducer is created.
Step 1
Create an interface for Shapes.
[Link]
public interface Shape {
void draw();
}
Step 2
Create concrete classes implementing the same interface.
[Link]
public class Rectangle implements Shape {
[Link] 6/110
10/14/2015 Design Pattern Quick Guide
@Override
public void draw() {
[Link]("Inside Rectangle::draw() method.");
}
}
[Link]
public class Square implements Shape {
@Override
public void draw() {
[Link]("Inside Square::draw() method.");
}
}
[Link]
public class Circle implements Shape {
@Override
public void draw() {
[Link]("Inside Circle::draw() method.");
}
}
Step 3
Create an interface for Colors.
[Link]
public interface Color {
void fill();
}
Step4
Create concrete classes implementing the same interface.
[Link]
public class Red implements Color {
@Override
public void fill() {
[Link]("Inside Red::fill() method.");
}
}
[Link]
[Link] 7/110
10/14/2015 Design Pattern Quick Guide
public class Green implements Color {
@Override
public void fill() {
[Link]("Inside Green::fill() method.");
}
}
[Link]
public class Blue implements Color {
@Override
public void fill() {
[Link]("Inside Blue::fill() method.");
}
}
Step 5
Create an Abstract class to get factories for Color and Shape Objects.
[Link]
public abstract class AbstractFactory {
abstract Color getColor(String color);
abstract Shape getShape(String shape) ;
}
Step 6
Create Factory classes extending AbstractFactory to generate object of concrete
class based on given information.
[Link]
public class ShapeFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if([Link]("CIRCLE")){
return new Circle();
} else if([Link]("RECTANGLE")){
return new Rectangle();
} else if([Link]("SQUARE")){
return new Square();
}
return null;
}
@Override
[Link] 8/110
10/14/2015 Design Pattern Quick Guide
Color getColor(String color) {
return null;
}
}
[Link]
public class ColorFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
return null;
}
@Override
Color getColor(String color) {
if(color == null){
return null;
}
if([Link]("RED")){
return new Red();
} else if([Link]("GREEN")){
return new Green();
} else if([Link]("BLUE")){
return new Blue();
}
return null;
}
}
Step 7
Create a Factory generator/producer class to get factories by passing an
information such as Shape or Color
[Link]
public class FactoryProducer {
public static AbstractFactory getFactory(String choice){
if([Link]("SHAPE")){
return new ShapeFactory();
} else if([Link]("COLOR")){
return new ColorFactory();
}
return null;
}
}
Step 8
Use the FactoryProducer to get AbstractFactory in order to get factories of concrete
classes by passing an information such as type.
[Link]
[Link] 9/110
10/14/2015 Design Pattern Quick Guide
public class AbstractFactoryPatternDemo {
public static void main(String[] args) {
//get shape factory
AbstractFactory shapeFactory = [Link]("SHAPE");
//get an object of Shape Circle
Shape shape1 = [Link]("CIRCLE");
//call draw method of Shape Circle
[Link]();
//get an object of Shape Rectangle
Shape shape2 = [Link]("RECTANGLE");
//call draw method of Shape Rectangle
[Link]();
//get an object of Shape Square
Shape shape3 = [Link]("SQUARE");
//call draw method of Shape Square
[Link]();
//get color factory
AbstractFactory colorFactory = [Link]("COLOR");
//get an object of Color Red
Color color1 = [Link]("RED");
//call fill method of Red
[Link]();
//get an object of Color Green
Color color2 = [Link]("Green");
//call fill method of Green
[Link]();
//get an object of Color Blue
Color color3 = [Link]("BLUE");
//call fill method of Color Blue
[Link]();
}
}
Step 9
Verify the output.
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.
Inside Red::fill() method.
Inside Green::fill() method.
[Link] 10/110
10/14/2015 Design Pattern Quick Guide
Inside Blue::fill() method.
Singleton Pattern
Singleton pattern is one of the simplest design patterns in Java. This type of design
pattern comes under creational pattern as this pattern provides one of the best way
to create an object.
This pattern involves a single class which is responsible to creates own object while
making sure that only single object get created. This class provides a way to
access its only object which can be accessed directly without need to instantiate
the object of the class.
Implementation
We're going to create a SingleObject class. SingleObject class have its constructor
as private and have a static instance of itself.
SingleObject class provides a static method to get its static instance to outside
world. SingletonPatternDemo, our demo class will use SingleObject class to get a
SingleObject object.
Step 1
Create a Singleton Class.
[Link] 11/110
10/14/2015 Design Pattern Quick Guide
[Link]
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
public void showMessage(){
[Link]("Hello World!");
}
}
Step 2
Get the only object from the singleton class.
[Link]
public class SingletonPatternDemo {
public static void main(String[] args) {
//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();
//Get the only object available
SingleObject object = [Link]();
//show the message
[Link]();
}
}
Step 3
Verify the output.
Hello World!
Builder Pattern
Builder pattern builds a complex object using simple objects and using a step by
step approach. This type of design pattern comes under creational pattern as this
pattern provides one of the best ways to create an object.
[Link] 12/110
10/14/2015 Design Pattern Quick Guide
A Builder class builds the final object step by step. This builder is independent of
other objects.
Implementation
We've considered a business case of fastfood restaurant where a typical meal
could be a burger and a cold drink. Burger could be either a Veg Burger or Chicken
Burger and will be packed by a wrapper. Cold drink could be either a coke or pepsi
and will be packed in a bottle.
We're going to create an Item interface representing food items such as burgers
and cold drinks and concrete classes implementing the Item interface and a
Packing interface representing packaging of food items and concrete classes
implementing the Packing interface as burger would be packed in wrapper and cold
drink would be packed as bottle.
We then create a Meal class having ArrayList of Item and a MealBuilder to build
different types of Meal object by combining Item. BuilderPatternDemo, our demo
class will use MealBuilder to build a Meal.
Step 1
Create an interface Item representing food item and packing.
[Link] 13/110
10/14/2015 Design Pattern Quick Guide
[Link]
public interface Item {
public String name();
public Packing packing();
public float price();
}
[Link]
public interface Packing {
public String pack();
}
Step 2
Create concreate classes implementing the Packing interface.
[Link]
public class Wrapper implements Packing {
@Override
public String pack() {
return "Wrapper";
}
}
[Link]
public class Bottle implements Packing {
@Override
public String pack() {
return "Bottle";
}
}
Step 3
Create abstract classes implementing the item interface providing default
functionalities.
[Link]
public abstract class Burger implements Item {
@Override
public Packing packing() {
return new Wrapper();
}
@Override
[Link] 14/110
10/14/2015 Design Pattern Quick Guide
public abstract float price();
}
[Link]
public abstract class ColdDrink implements Item {
@Override
public Packing packing() {
return new Bottle();
}
@Override
public abstract float price();
}
Step 4
Create concrete classes extending Burger and ColdDrink classes
[Link]
public class VegBurger extends Burger {
@Override
public float price() {
return 25.0f;
}
@Override
public String name() {
return "Veg Burger";
}
}
[Link]
public class ChickenBurger extends Burger {
@Override
public float price() {
return 50.5f;
}
@Override
public String name() {
return "Chicken Burger";
}
}
[Link]
public class Coke extends ColdDrink {
@Override
public float price() {
[Link] 15/110
10/14/2015 Design Pattern Quick Guide
return 30.0f;
}
@Override
public String name() {
return "Coke";
}
}
[Link]
public class Pepsi extends ColdDrink {
@Override
public float price() {
return 35.0f;
}
@Override
public String name() {
return "Pepsi";
}
}
Step 5
Create a Meal class having Item objects defined above.
[Link]
import [Link];
import [Link];
public class Meal {
private List<Item> items = new ArrayList<Item>();
public void addItem(Item item){
[Link](item);
}
public float getCost(){
float cost = 0.0f;
for (Item item : items) {
cost += [Link]();
}
return cost;
}
public void showItems(){
for (Item item : items) {
[Link]("Item : "+[Link]());
[Link](", Packing : "+[Link]().pack());
[Link](", Price : "+[Link]());
}
}
}
[Link] 16/110
10/14/2015 Design Pattern Quick Guide
Step 6
Create a MealBuilder class, the actual builder class responsible to create Meal
objects.
[Link]
public class MealBuilder {
public Meal prepareVegMeal (){
Meal meal = new Meal();
[Link](new VegBurger());
[Link](new Coke());
return meal;
}
public Meal prepareNonVegMeal (){
Meal meal = new Meal();
[Link](new ChickenBurger());
[Link](new Pepsi());
return meal;
}
}
Step 7
BuiderPatternDemo uses MealBuider to demonstrate builder pattern.
[Link]
public class BuilderPatternDemo {
public static void main(String[] args) {
MealBuilder mealBuilder = new MealBuilder();
Meal vegMeal = [Link]();
[Link]("Veg Meal");
[Link]();
[Link]("Total Cost: " +[Link]());
Meal nonVegMeal = [Link]();
[Link]("\n\nNon‐Veg Meal");
[Link]();
[Link]("Total Cost: " +[Link]());
}
}
Step 8
Verify the output.
Veg Meal
Item : Veg Burger, Packing : Wrapper, Price : 25.0
[Link] 17/110
10/14/2015 Design Pattern Quick Guide
Item : Coke, Packing : Bottle, Price : 30.0
Total Cost: 55.0
Non‐Veg Meal
Item : Chicken Burger, Packing : Wrapper, Price : 50.5
Item : Pepsi, Packing : Bottle, Price : 35.0
Total Cost: 85.5
Prototype Pattern
Prototype pattern refers to creating duplicate object while keeping performance in
mind. This type of design pattern comes under creational pattern as this pattern
provides one of the best way to create an object.
This pattern involves implementing a prototype interface which tells to create a
clone of the current object. This pattern is used when creation of object directly is
costly. For example, a object is to be created after a costly database operation. We
can cache the object, returns its clone on next request and update the database as
as and when needed thus reducing database calls.
Implementation
We're going to create an abstract class Shape and concrete classes extending the
Shape class. A class ShapeCache is defined as a next step which stores shape
objects in a Hashtable and returns their clone when requested.
PrototypPatternDemo, our demo class will use ShapeCache class to get a Shape
object.
[Link] 18/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create an abstract class implementing Clonable interface.
[Link]
public abstract class Shape implements Cloneable {
private String id;
protected String type;
abstract void draw();
public String getType(){
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
[Link] = id;
}
public Object clone() {
Object clone = null;
try {
clone = [Link]();
} catch (CloneNotSupportedException e) {
[Link]();
}
return clone;
}
}
[Link] 19/110
10/14/2015 Design Pattern Quick Guide
Step 2
Create concrete classes extending the above class.
[Link]
public class Rectangle extends Shape {
public Rectangle(){
type = "Rectangle";
}
@Override
public void draw() {
[Link]("Inside Rectangle::draw() method.");
}
}
[Link]
public class Square extends Shape {
public Square(){
type = "Square";
}
@Override
public void draw() {
[Link]("Inside Square::draw() method.");
}
}
[Link]
public class Circle extends Shape {
public Circle(){
type = "Circle";
}
@Override
public void draw() {
[Link]("Inside Circle::draw() method.");
}
}
Step 3
Create a class to get concreate classes from database and store them in a
Hashtable.
[Link]
[Link] 20/110
10/14/2015 Design Pattern Quick Guide
import [Link];
public class ShapeCache {
private static Hashtable<String, Shape> shapeMap
= new Hashtable<String, Shape>();
public static Shape getShape(String shapeId) {
Shape cachedShape = [Link](shapeId);
return (Shape) [Link]();
}
// for each shape run database query and create shape
// [Link](shapeKey, shape);
// for example, we are adding three shapes
public static void loadCache() {
Circle circle = new Circle();
[Link]("1");
[Link]([Link](),circle);
Square square = new Square();
[Link]("2");
[Link]([Link](),square);
Rectangle rectangle = new Rectangle();
[Link]("3");
[Link]([Link](),rectangle);
}
}
Step 4
PrototypePatternDemo uses ShapeCache class to get clones of shapes stored in a
Hashtable.
[Link]
public class PrototypePatternDemo {
public static void main(String[] args) {
[Link]();
Shape clonedShape = (Shape) [Link]("1");
[Link]("Shape : " + [Link]());
Shape clonedShape2 = (Shape) [Link]("2");
[Link]("Shape : " + [Link]());
Shape clonedShape3 = (Shape) [Link]("3");
[Link]("Shape : " + [Link]());
}
}
Step 5
Verify the output.
[Link] 21/110
10/14/2015 Design Pattern Quick Guide
Shape : Circle
Shape : Square
Shape : Rectangle
Adapter Pattern
Adapter pattern works as a bridge between two incompatible interfaces. This type
of design pattern comes under structural pattern as this pattern combines the
capability of two independent interfaces.
This pattern involves a single class which is responsible to join functionalities of
independent or incompatible interfaces. A real life example could be a case of card
reader which acts as an adapter between memory card and a laptop. You plugins
the memory card into card reader and card reader into the laptop so that memory
card can be read via laptop.
We are demonstrating use of Adapter pattern via following example in which an
audio player device can play mp3 files only and wants to use an advanced audio
player capable of playing vlc and mp4 files.
Implementation
We've an interface MediaPlayer interface and a concrete class AudioPlayer
implementing the MediaPlayer interface. AudioPlayer can play mp3 format audio
files by default.
We want to make AudioPlayer to play other formats as well. To attain this, we've
created an adapter class MediaAdapter which implements the MediaPlayer interface
and uses AdvancedMediaPlayer objects to play the required format.
AudioPlayer uses the adapter class MediaAdapter passing it the desired audio type
without knowing the actual class which can play the desired format.
AdapterPatternDemo, our demo class will use AudioPlayer class to play various
formats.
[Link] 22/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create interfaces for Media Player and Advanced Media Player.
[Link]
public interface MediaPlayer {
public void play(String audioType, String fileName);
}
[Link]
public interface AdvancedMediaPlayer {
public void playVlc(String fileName);
public void playMp4(String fileName);
}
Step 2
Create concrete classes implementing the AdvancedMediaPlayer interface.
[Link]
public class VlcPlayer implements AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
[Link]("Playing vlc file. Name: "+ fileName);
}
@Override
[Link] 23/110
10/14/2015 Design Pattern Quick Guide
public void playMp4(String fileName) {
//do nothing
}
}
[Link]
public class Mp4Player implements AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
//do nothing
}
@Override
public void playMp4(String fileName) {
[Link]("Playing mp4 file. Name: "+ fileName);
}
}
Step 3
Create adapter class implementing the MediaPlayer interface.
[Link]
public class MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMusicPlayer;
public MediaAdapter(String audioType){
if([Link]("vlc") ){
advancedMusicPlayer = new VlcPlayer();
} else if ([Link]("mp4")){
advancedMusicPlayer = new Mp4Player();
}
}
@Override
public void play(String audioType, String fileName) {
if([Link]("vlc")){
[Link](fileName);
}else if([Link]("mp4")){
advancedMusicPlayer.playMp4(fileName);
}
}
}
Step 4
Create concrete class implementing the MediaPlayer interface.
[Link]
public class AudioPlayer implements MediaPlayer {
[Link] 24/110
10/14/2015 Design Pattern Quick Guide
MediaAdapter mediaAdapter;
@Override
public void play(String audioType, String fileName) {
//inbuilt support to play mp3 music files
if([Link]("mp3")){
[Link]("Playing mp3 file. Name: "+ fileName);
}
//mediaAdapter is providing support to play other file formats
else if([Link]("vlc")
|| [Link]("mp4")){
mediaAdapter = new MediaAdapter(audioType);
[Link](audioType, fileName);
}
else{
[Link]("Invalid media. "+
audioType + " format not supported");
}
}
}
Step 5
Use the AudioPlayer to play different types of audio formats.
[Link]
public class AdapterPatternDemo {
public static void main(String[] args) {
AudioPlayer audioPlayer = new AudioPlayer();
[Link]("mp3", "beyond the horizon.mp3");
[Link]("mp4", "alone.mp4");
[Link]("vlc", "far far [Link]");
[Link]("avi", "mind [Link]");
}
}
Step 6
Verify the output.
Playing mp3 file. Name: beyond the horizon.mp3
Playing mp4 file. Name: alone.mp4
Playing vlc file. Name: far far [Link]
Invalid media. avi format not supported
Bridge Pattern
Bridge is used where we need to decouple an abstraction from its implementation
so that the two can vary independently. This type of design pattern comes under
structural pattern as this pattern decouples implementation class and abstract
[Link] 25/110
10/14/2015 Design Pattern Quick Guide
class by providing a bridge structure between them.
This pattern involves an interface which acts as a bridge which makes the
functionality of concrete classes independent from interface implementer classes.
Both types of classes can be altered structurally without affecting each other.
We are demonstrating use of Bridge pattern via following example in which a circle
can be drawn in different colors using same abstract class method but different
bridge implementer classes.
Implementation
We've an interface DrawAPI interface which is acting as a bridge implementer and
concrete classes RedCircle, GreenCircle implementing the DrawAPI interface. Shape
is an abstract class and will use object of DrawAPI. BridgePatternDemo, our demo
class will use Shape class to draw different colored circle.
Step 1
Create bridge implementer interface.
[Link]
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
Step 2
Create concrete bridge implementer classes implementing the DrawAPI interface.
[Link] 26/110
10/14/2015 Design Pattern Quick Guide
[Link]
public class RedCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
[Link]("Drawing Circle[ color: red, radius: "
+ radius +", x: " +x+", "+ y +"]");
}
}
[Link]
public class GreenCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
[Link]("Drawing Circle[ color: green, radius: "
+ radius +", x: " +x+", "+ y +"]");
}
}
Step 3
Create an abstract class Shape using the DrawAPI interface.
[Link]
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
[Link] = drawAPI;
}
public abstract void draw();
}
Step 4
Create concrete class implementing the Shape interface.
[Link]
public class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int radius, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
[Link] = radius;
}
public void draw() {
[Link](radius,x,y);
}
}
[Link] 27/110
10/14/2015 Design Pattern Quick Guide
Step 5
Use the Shape and DrawAPI classes to draw different colored circles.
[Link]
public class BridgePatternDemo {
public static void main(String[] args) {
Shape redCircle = new Circle(100,100, 10, new RedCircle());
Shape greenCircle = new Circle(100,100, 10, new GreenCircle());
[Link]();
[Link]();
}
}
Step 6
Verify the output.
Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[ color: green, radius: 10, x: 100, 100]
Filter/Criteria Pattern
Filter pattern or Criteria pattern is a design pattern that enables developers to filter
a set of objects, using different criteria, chaining them in a decoupled way through
logical operations. This type of design pattern comes under structural pattern as
this pattern is combining multiple criteria to obtain single criteria.
Implementation
We're going to create a Person object, Criteria interface and concrete classes
implementing this interface to filter list of Person objects. CriteriaPatternDemo, our
demo class uses Criteria objects to filter List of Person objects based on various
criteria and their combinations.
[Link] 28/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create a class on which criteria is to be applied.
[Link]
public class Person {
private String name;
private String gender;
private String maritalStatus;
public Person(String name,String gender,String maritalStatus){
[Link] = name;
[Link] = gender;
[Link] = maritalStatus;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getMaritalStatus() {
return maritalStatus;
}
}
Step 2
[Link] 29/110
10/14/2015 Design Pattern Quick Guide
Create an interface for Criteria.
[Link]
import [Link];
public interface Criteria {
public List<Person> meetCriteria(List<Person> persons);
}
Step 3
Create concrete classes implementing the Criteria interface.
[Link]
import [Link];
import [Link];
public class CriteriaMale implements Criteria {
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> malePersons = new ArrayList<Person>();
for (Person person : persons) {
if([Link]().equalsIgnoreCase("MALE")){
[Link](person);
}
}
return malePersons;
}
}
[Link]
import [Link];
import [Link];
public class CriteriaFemale implements Criteria {
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> femalePersons = new ArrayList<Person>();
for (Person person : persons) {
if([Link]().equalsIgnoreCase("FEMALE")){
[Link](person);
}
}
return femalePersons;
}
}
[Link]
import [Link];
[Link] 30/110
10/14/2015 Design Pattern Quick Guide
import [Link];
public class CriteriaSingle implements Criteria {
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> singlePersons = new ArrayList<Person>();
for (Person person : persons) {
if([Link]().equalsIgnoreCase("SINGLE")){
[Link](person);
}
}
return singlePersons;
}
}
[Link]
import [Link];
public class AndCriteria implements Criteria {
private Criteria criteria;
private Criteria otherCriteria;
public AndCriteria(Criteria criteria, Criteria otherCriteria) {
[Link] = criteria;
[Link] = otherCriteria;
}
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> firstCriteriaPersons = [Link](persons);
return [Link](firstCriteriaPersons);
}
}
[Link]
import [Link];
public class AndCriteria implements Criteria {
private Criteria criteria;
private Criteria otherCriteria;
public AndCriteria(Criteria criteria, Criteria otherCriteria) {
[Link] = criteria;
[Link] = otherCriteria;
}
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> firstCriteriaItems = [Link](persons);
List<Person> otherCriteriaItems = [Link](persons);
for (Person person : otherCriteriaItems) {
if(){
[Link](person);
[Link] 31/110
10/14/2015 Design Pattern Quick Guide
}
}
return firstCriteriaItems;
}
}
Step4
Use different Criteria and their combination to filter out persons.
[Link]
public class CriteriaPatternDemo {
public static void main(String[] args) {
List<Person> persons = new ArrayList<Person>();
[Link](new Person("Robert","Male", "Single"));
[Link](new Person("John","Male", "Married"));
[Link](new Person("Laura","Female", "Married"));
[Link](new Person("Diana","Female", "Single"));
[Link](new Person("Mike","Male", "Single"));
[Link](new Person("Bobby","Male", "Single"));
Criteria male = new CriteriaMale();
Criteria female = new CriteriaFemale();
Criteria single = new CriteriaSingle();
Criteria singleMale = new AndCriteria(single, male);
Criteria singleOrFemale = new OrCriteria(single, female);
[Link]("Males: ");
printPersons([Link](persons));
[Link]("\nFemales: ");
printPersons([Link](persons));
[Link]("\nSingle Males: ");
printPersons([Link](persons));
[Link]("\nSingle Or Females: ");
printPersons([Link](persons));
}
public static void printPersons(List<Person> persons){
for (Person person : persons) {
[Link]("Person : [ Name : " + [Link]()
+", Gender : " + [Link]()
+", Marital Status : " + [Link]()
+" ]");
}
}
}
Step 5
Verify the output.
[Link] 32/110
10/14/2015 Design Pattern Quick Guide
Males:
Person : [ Name : Robert, Gender : Male, Marital Status : Single ]
Person : [ Name : John, Gender : Male, Marital Status : Married ]
Person : [ Name : Mike, Gender : Male, Marital Status : Single ]
Person : [ Name : Bobby, Gender : Male, Marital Status : Single ]
Females:
Person : [ Name : Laura, Gender : Female, Marital Status : Married ]
Person : [ Name : Diana, Gender : Female, Marital Status : Single ]
Single Males:
Person : [ Name : Robert, Gender : Male, Marital Status : Single ]
Person : [ Name : Mike, Gender : Male, Marital Status : Single ]
Person : [ Name : Bobby, Gender : Male, Marital Status : Single ]
Single Or Females:
Person : [ Name : Robert, Gender : Male, Marital Status : Single ]
Person : [ Name : Diana, Gender : Female, Marital Status : Single ]
Person : [ Name : Mike, Gender : Male, Marital Status : Single ]
Person : [ Name : Bobby, Gender : Male, Marital Status : Single ]
Person : [ Name : Laura, Gender : Female, Marital Status : Married ]
Composite Pattern
Composite pattern is used where we need to treat a group of objects in similar way
as a single object. Composite pattern composes objects in term of a tree structure
to represent part as well as whole hierarchy . This type of design pattern comes
under structural pattern as this pattern creates a tree structure of group of objects.
This pattern creates a class contains group of its own objects. This class provides
ways to modify its group of same objects.
We are demonstrating use of Composite pattern via following example in which
show employees hierarchy of an organization.
Implementation
We've a class Employee which acts as composite pattern actor class.
CompositePatternDemo, our demo class will use Employee class to add department
level hierarchy and print all employees.
[Link] 33/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create Employee class having list of Employee objects.
[Link]
import [Link];
import [Link];
public class Employee {
private String name;
private String dept;
private int salary;
private List<Employee> subordinates;
// constructor
public Employee(String name,String dept, int sal) {
[Link] = name;
[Link] = dept;
[Link] = sal;
subordinates = new ArrayList<Employee>();
}
public void add(Employee e) {
[Link](e);
}
public void remove(Employee e) {
[Link](e);
}
[Link] 34/110
10/14/2015 Design Pattern Quick Guide
public List<Employee> getSubordinates(){
return subordinates;
}
public String toString(){
return ("Employee :[ Name : "+ name
+", dept : "+ dept + ", salary :"
+ salary+" ]");
}
}
Step 2
Use the Employee class to create and print employee hierarchy.
[Link]
public class CompositePatternDemo {
public static void main(String[] args) {
Employee CEO = new Employee("John","CEO", 30000);
Employee headSales = new Employee("Robert","Head Sales", 20000);
Employee headMarketing = new Employee("Michel","Head Marketing", 20000);
Employee clerk1 = new Employee("Laura","Marketing", 10000);
Employee clerk2 = new Employee("Bob","Marketing", 10000);
Employee salesExecutive1 = new Employee("Richard","Sales", 10000);
Employee salesExecutive2 = new Employee("Rob","Sales", 10000);
[Link](headSales);
[Link](headMarketing);
[Link](salesExecutive1);
[Link](salesExecutive2);
[Link](clerk1);
[Link](clerk2);
//print all employees of the organization
[Link](CEO);
for (Employee headEmployee : [Link]()) {
[Link](headEmployee);
for (Employee employee : [Link]()) {
[Link](employee);
}
}
}
}
Step 3
Verify the output.
Employee :[ Name : John, dept : CEO, salary :30000 ]
[Link] 35/110
10/14/2015 Design Pattern Quick Guide
Employee :[ Name : Robert, dept : Head Sales, salary :20000 ]
Employee :[ Name : Richard, dept : Sales, salary :10000 ]
Employee :[ Name : Rob, dept : Sales, salary :10000 ]
Employee :[ Name : Michel, dept : Head Marketing, salary :20000 ]
Employee :[ Name : Laura, dept : Marketing, salary :10000 ]
Employee :[ Name : Bob, dept : Marketing, salary :10000 ]
Decorator Pattern
Decorator pattern allows to add new functionality an existing object without altering
its structure. This type of design pattern comes under structural pattern as this
pattern acts as a wrapper to existing class.
This pattern creates a decorator class which wraps the original class and provides
additional functionality keeping class methods signature intact.
We are demonstrating use of Decorator pattern via following example in which we'll
decorate a shape with some color without alter shape class.
Implementation
We're going to create a Shape interface and concrete classes implementing the
Shape interface. We then create a abstract decorator class ShapeDecorator
implementing the Shape interface and having Shape object as its instance variable.
RedShapeDecorator is concrete class implementing ShapeDecorator.
[Link] 36/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create an interface.
[Link]
public interface Shape {
void draw();
}
Step 2
Create concrete classes implementing the same interface.
[Link]
public class Rectangle implements Shape {
@Override
public void draw() {
[Link]("Shape: Rectangle");
}
}
[Link]
public class Circle implements Shape {
@Override
public void draw() {
[Link]("Shape: Circle");
[Link] 37/110
10/14/2015 Design Pattern Quick Guide
}
}
Step 3
Create abstract decorator class implementing the Shape interface.
[Link]
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape){
[Link] = decoratedShape;
}
public void draw(){
[Link]();
}
}
Step 4
Create concrete decorator class extending the ShapeDecorator class.
[Link]
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
@Override
public void draw() {
[Link]();
setRedBorder(decoratedShape);
}
private void setRedBorder(Shape decoratedShape){
[Link]("Border Color: Red");
}
}
Step 5
Use the RedShapeDecorator to decorate Shape objects.
[Link]
public class DecoratorPatternDemo {
public static void main(String[] args) {
[Link] 38/110
10/14/2015 Design Pattern Quick Guide
Shape circle = new Circle();
Shape redCircle = new RedShapeDecorator(new Circle());
Shape redRectangle = new RedShapeDecorator(new Rectangle());
[Link]("Circle with normal border");
[Link]();
[Link]("\nCircle of red border");
[Link]();
[Link]("\nRectangle of red border");
[Link]();
}
}
Step 6
Verify the output.
Circle with normal border
Shape: Circle
Circle of red border
Shape: Circle
Border Color: Red
Rectangle of red border
Shape: Rectangle
Border Color: Red
Facade Pattern
Facade pattern hides the complexities of the system and provides an interface to
the client using which the client can access the system. This type of design pattern
comes under structural pattern as this pattern adds an interface to exiting system
to hide its complexities.
This pattern involves a single class which provides simplified methods which are
required by client and delegates calls to existing system classes methods.
Implementation
We're going to create a Shape interface and concrete classes implementing the
Shape interface. A facade class ShapeMaker is defined as a next step.
ShapeMaker class uses the concrete classes to delegates user calls to these
classes. FacadePatternDemo, our demo class will use ShapeMaker class to show
[Link] 39/110
10/14/2015 Design Pattern Quick Guide
the results.
Step 1
Create an interface.
[Link]
public interface Shape {
void draw();
}
Step 2
Create concrete classes implementing the same interface.
[Link]
public class Rectangle implements Shape {
@Override
public void draw() {
[Link]("Rectangle::draw()");
}
}
[Link]
public class Square implements Shape {
@Override
public void draw() {
[Link]("Square::draw()");
}
}
[Link] 40/110
10/14/2015 Design Pattern Quick Guide
[Link]
public class Circle implements Shape {
@Override
public void draw() {
[Link]("Circle::draw()");
}
}
Step 3
Create a facade class.
[Link]
public class ShapeMaker {
private Shape circle;
private Shape rectangle;
private Shape square;
public ShapeMaker() {
circle = new Circle();
rectangle = new Rectangle();
square = new Square();
}
public void drawCircle(){
[Link]();
}
public void drawRectangle(){
[Link]();
}
public void drawSquare(){
[Link]();
}
}
Step 4
Use the facade to draw various types of shapes.
[Link]
public class FacadePatternDemo {
public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();
[Link]();
[Link]();
[Link]();
}
}
[Link] 41/110
10/14/2015 Design Pattern Quick Guide
Step 5
Verify the output.
Circle::draw()
Rectangle::draw()
Square::draw()
Flyweight Pattern
Flyweight pattern is primarily used to reduce the number of objects created, to
decrease memory footprint and increase performance. This type of design pattern
comes under structural pattern as this pattern provides ways to decrease objects
count thus improving application required objects structure.
Flyweight pattern try to reuse already existing similar kind objects by storing them
and creates new object when no matching object is found. We'll demonstrate this
pattern by drawing 20 circle of different locations but we'll creating only 5 objects.
Only 5 colors are available so color property is used to check already existing Circle
objects.
Implementation
We're going to create a Shape interface and concrete class Circle implementing the
Shape interface. A factory class ShapeFactory is defined as a next step.
ShapeFactory have a HashMap of Circle having key as color of the Circle object.
Whenever a request comes to create a circle of particular color to ShapeFactory.
ShapeFactory checks the circle object in its HashMap, if object of Circle found, that
object is returned otherwise a new object is created, stored in hashmap for future
use and returned to client.
FlyWeightPatternDemo, our demo class will use ShapeFactory to get a Shape
object. It will pass information (red / green / blue/ black / white) to ShapeFactory
to get the circle of desired color it needs.
[Link] 42/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create an interface.
[Link]
public interface Shape {
void draw();
}
Step 2
Create concrete class implementing the same interface.
[Link]
public class Circle implements Shape {
private String color;
private int x;
private int y;
private int radius;
public Circle(String color){
[Link] = color;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
[Link] 43/110
10/14/2015 Design Pattern Quick Guide
public void setRadius(int radius) {
[Link] = radius;
}
@Override
public void draw() {
[Link]("Circle: Draw() [Color : " + color
+", x : " + x +", y :" + y +", radius :" + radius);
}
}
Step 3
Create a Factory to generate object of concrete class based on given information.
[Link]
import [Link];
public class ShapeFactory {
private static final HashMap<String, Shape> circleMap = new HashMap();
public static Shape getCircle(String color) {
Circle circle = (Circle)[Link](color);
if(circle == null) {
circle = new Circle(color);
[Link](color, circle);
[Link]("Creating circle of color : " + color);
}
return circle;
}
}
Step 4
Use the Factory to get object of concrete class by passing an information such as
color.
[Link]
public class FlyweightPatternDemo {
private static final String colors[] =
{ "Red", "Green", "Blue", "White", "Black" };
public static void main(String[] args) {
for(int i=0; i < 20; ++i) {
Circle circle =
(Circle)[Link](getRandomColor());
[Link](getRandomX());
[Link](getRandomY());
[Link](100);
[Link]();
}
[Link] 44/110
10/14/2015 Design Pattern Quick Guide
}
private static String getRandomColor() {
return colors[(int)([Link]()*[Link])];
}
private static int getRandomX() {
return (int)([Link]()*100 );
}
private static int getRandomY() {
return (int)([Link]()*100);
}
}
Step 5
Verify the output.
Creating circle of color : Black
Circle: Draw() [Color : Black, x : 36, y :71, radius :100
Creating circle of color : Green
Circle: Draw() [Color : Green, x : 27, y :27, radius :100
Creating circle of color : White
Circle: Draw() [Color : White, x : 64, y :10, radius :100
Creating circle of color : Red
Circle: Draw() [Color : Red, x : 15, y :44, radius :100
Circle: Draw() [Color : Green, x : 19, y :10, radius :100
Circle: Draw() [Color : Green, x : 94, y :32, radius :100
Circle: Draw() [Color : White, x : 69, y :98, radius :100
Creating circle of color : Blue
Circle: Draw() [Color : Blue, x : 13, y :4, radius :100
Circle: Draw() [Color : Green, x : 21, y :21, radius :100
Circle: Draw() [Color : Blue, x : 55, y :86, radius :100
Circle: Draw() [Color : White, x : 90, y :70, radius :100
Circle: Draw() [Color : Green, x : 78, y :3, radius :100
Circle: Draw() [Color : Green, x : 64, y :89, radius :100
Circle: Draw() [Color : Blue, x : 3, y :91, radius :100
Circle: Draw() [Color : Blue, x : 62, y :82, radius :100
Circle: Draw() [Color : Green, x : 97, y :61, radius :100
Circle: Draw() [Color : Green, x : 86, y :12, radius :100
Circle: Draw() [Color : Green, x : 38, y :93, radius :100
Circle: Draw() [Color : Red, x : 76, y :82, radius :100
Circle: Draw() [Color : Blue, x : 95, y :82, radius :100
Proxy Pattern
In Proxy pattern, a class represents functionality of another class. This type of
design pattern comes under structural pattern.
[Link] 45/110
10/14/2015 Design Pattern Quick Guide
In Proxy pattern, we create object having original object to interface its
functionality to outer world.
Implementation
We're going to create a Image interface and concrete classes implementing the
Image interface. ProxyImage is a a proxy class to reduce memory footprint of
RealImage object loading.
ProxyPatternDemo, our demo class will use ProxyImage to get a Image object to
load and display as it needs.
Step 1
Create an interface.
[Link]
public interface Image {
void display();
}
Step 2
Create concrete classes implementing the same interface.
[Link]
public class RealImage implements Image {
private String fileName;
public RealImage(String fileName){
[Link] = fileName;
[Link] 46/110
10/14/2015 Design Pattern Quick Guide
loadFromDisk(fileName);
}
@Override
public void display() {
[Link]("Displaying " + fileName);
}
private void loadFromDisk(String fileName){
[Link]("Loading " + fileName);
}
}
[Link]
public class ProxyImage implements Image{
private RealImage realImage;
private String fileName;
public ProxyImage(String fileName){
[Link] = fileName;
}
@Override
public void display() {
if(realImage == null){
realImage = new RealImage(fileName);
}
[Link]();
}
}
Step 3
Use the ProxyImage to get object of RealImage class when required.
[Link]
public class ProxyPatternDemo {
public static void main(String[] args) {
Image image = new ProxyImage("test_10mb.jpg");
//image will be loaded from disk
[Link]();
[Link]("");
//image will not be loaded from disk
[Link]();
}
}
Step 4
Verify the output.
[Link] 47/110
10/14/2015 Design Pattern Quick Guide
Loading test_10mb.jpg
Displaying test_10mb.jpg
Displaying test_10mb.jpg
Chain of Responsibility Pattern
As the name suggest, the chain of responsibility pattern creates a chain of receiver
objects for a request. This pattern decouples sender and receiver of a request
based on type of request. This pattern comes under behavioral patterns.
In this pattern, normally each receiver contains reference to another receiver. If
one object cannot handle the request then it passes the same to the next receiver
and so on.
Implementation
We've created an abstract class AbstractLogger with a level of logging. Then we've
created three types of loggers extending the AbstractLogger. Each logger checks
the level of message to its level and print accordingly otherwise does not print and
pass the message to its next logger.
Step 1
Create an abstract logger class.
[Link] 48/110
10/14/2015 Design Pattern Quick Guide
[Link]
public abstract class AbstractLogger {
public static int INFO = 1;
public static int DEBUG = 2;
public static int ERROR = 3;
protected int level;
//next element in chain or responsibility
protected AbstractLogger nextLogger;
public void setNextLogger(AbstractLogger nextLogger){
[Link] = nextLogger;
}
public void logMessage(int level, String message){
if([Link] <= level){
write(message);
}
if(nextLogger !=null){
[Link](level, message);
}
}
abstract protected void write(String message);
}
Step 2
Create concrete classes extending the logger.
[Link]
public class ConsoleLogger extends AbstractLogger {
public ConsoleLogger(int level){
[Link] = level;
}
@Override
protected void write(String message) {
[Link]("Standard Console::Logger: " + message);
}
}
[Link]
public class ErrorLogger extends AbstractLogger {
public ErrorLogger(int level){
[Link] = level;
}
@Override
protected void write(String message) {
[Link] 49/110
10/14/2015 Design Pattern Quick Guide
[Link]("Error Console::Logger: " + message);
}
}
[Link]
public class FileLogger extends AbstractLogger {
public FileLogger(int level){
[Link] = level;
}
@Override
protected void write(String message) {
[Link]("File::Logger: " + message);
}
}
Step 3
Create different types of loggers. Assign them error levels and set next logger in
each logger. Next logger in each logger represents the part of the chain.
[Link]
public class ChainPatternDemo {
private static AbstractLogger getChainOfLoggers(){
AbstractLogger errorLogger = new ErrorLogger([Link]);
AbstractLogger fileLogger = new FileLogger([Link]);
AbstractLogger consoleLogger = new ConsoleLogger([Link]);
[Link](fileLogger);
[Link](consoleLogger);
return errorLogger;
}
public static void main(String[] args) {
AbstractLogger loggerChain = getChainOfLoggers();
[Link]([Link],
"This is an information.");
[Link]([Link],
"This is an debug level information.");
[Link]([Link],
"This is an error information.");
}
}
Step 4
[Link] 50/110
10/14/2015 Design Pattern Quick Guide
Verify the output.
Standard Console::Logger: This is an information.
File::Logger: This is an debug level information.
Standard Console::Logger: This is an debug level information.
Error Console::Logger: This is an error information.
File::Logger: This is an error information.
Standard Console::Logger: This is an error information.
Command Pattern
Command pattern is a data driven design pattern and falls under behavioral pattern
category. A request is wrapped under a object as command and passed to invoker
object. Invoker object looks for the appropriate object which can handle this
command and pass the command to the corresponding object and that object
executes the command.
Implementation
We've created an interface Order which is acting as a command. We've created a
Stock class which acts as a request. We've concrete command classes BuyStock
and SellStock implementing Order interface which will do actual command
processing. A class Broker is created which acts as a invoker object. It can take
order and place orders.
Broker object uses command pattern to identify which object will execute which
command based on type of command. CommandPatternDemo, our demo class will
use Broker class to demonstrate command pattern.
[Link] 51/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create a command interface.
[Link]
public interface Order {
void execute();
}
Step 2
Create a request class.
[Link]
public class Stock {
private String name = "ABC";
private int quantity = 10;
public void buy(){
[Link]("Stock [ Name: "+name+",
Quantity: " + quantity +" ] bought");
}
public void sell(){
[Link]("Stock [ Name: "+name+",
Quantity: " + quantity +" ] sold");
}
[Link] 52/110
10/14/2015 Design Pattern Quick Guide
Step 3
Create concrete classes implementing the Order interface.
[Link]
public class BuyStock implements Order {
private Stock abcStock;
public BuyStock(Stock abcStock){
[Link] = abcStock;
}
public void execute() {
[Link]();
}
}
[Link]
public class SellStock implements Order {
private Stock abcStock;
public SellStock(Stock abcStock){
[Link] = abcStock;
}
public void execute() {
[Link]();
}
}
Step 4
Create command invoker class.
[Link]
import [Link];
import [Link];
public class Broker {
private List<Order> orderList = new ArrayList<Order>();
public void takeOrder(Order order){
[Link](order);
}
public void placeOrders(){
for (Order order : orderList) {
[Link]();
}
[Link]();
[Link] 53/110
10/14/2015 Design Pattern Quick Guide
}
}
Step 5
Use the Broker class to take and execute commands.
[Link]
public class CommandPatternDemo {
public static void main(String[] args) {
Stock abcStock = new Stock();
BuyStock buyStockOrder = new BuyStock(abcStock);
SellStock sellStockOrder = new SellStock(abcStock);
Broker broker = new Broker();
[Link](buyStockOrder);
[Link](sellStockOrder);
[Link]();
}
}
Step 6
Verify the output.
Stock [ Name: ABC, Quantity: 10 ] bought
Stock [ Name: ABC, Quantity: 10 ] sold
Interpreter Pattern
Interpreter pattern provides way to evaluate language grammar or expression. This
type of pattern comes under behavioral patterns. This pattern involves
implementing a expression interface which tells to interpret a particular context.
This pattern is used in SQL parsing, symbol processing engine etc.
Implementation
We're going to create an interface Expression and concrete classes implementing
the Expression interface. A class TerminalExpression is defined which acts as a
main interpreter of context in question. Other classes OrExpression, AndExpression
are used to create combinational expressions.
InterpreterPatternDemo, our demo class will use Expression class to create rules
and demonstrate parsing of expressions.
[Link] 54/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create an expression interface.
[Link]
public interface Expression {
public boolean interpret(String context);
}
Step 2
Create concrete classes implementing the above interface.
[Link]
public class TerminalExpression implements Expression {
private String data;
public TerminalExpression(String data){
[Link] = data;
}
@Override
[Link] 55/110
10/14/2015 Design Pattern Quick Guide
public boolean interpret(String context) {
if([Link](data)){
return true;
}
return false;
}
}
[Link]
public class OrExpression implements Expression {
private Expression expr1 = null;
private Expression expr2 = null;
public OrExpression(Expression expr1, Expression expr2) {
this.expr1 = expr1;
this.expr2 = expr2;
}
@Override
public boolean interpret(String context) {
return [Link](context) || [Link](context);
}
}
[Link]
public class AndExpression implements Expression {
private Expression expr1 = null;
private Expression expr2 = null;
public AndExpression(Expression expr1, Expression expr2) {
this.expr1 = expr1;
this.expr2 = expr2;
}
@Override
public boolean interpret(String context) {
return [Link](context) && [Link](context);
}
}
Step 3
InterpreterPatternDemo uses Expression class to create rules and then parse them.
[Link]
public class InterpreterPatternDemo {
//Rule: Robert and John are male
public static Expression getMaleExpression(){
Expression robert = new TerminalExpression("Robert");
Expression john = new TerminalExpression("John");
return new OrExpression(robert, john);
[Link] 56/110
10/14/2015 Design Pattern Quick Guide
}
//Rule: Julie is a married women
public static Expression getMarriedWomanExpression(){
Expression julie = new TerminalExpression("Julie");
Expression married = new TerminalExpression("Married");
return new AndExpression(julie, married);
}
public static void main(String[] args) {
Expression isMale = getMaleExpression();
Expression isMarriedWoman = getMarriedWomanExpression();
[Link]("John is male? " + [Link]("John"));
[Link]("Julie is a married women? "
+ [Link]("Married Julie"));
}
}
Step 4
Verify the output.
John is male? true
Julie is a married women? true
Iterator Pattern
Iterator pattern is very commonly used design pattern in Java and .Net
programming environment. This pattern is used to get a way to access the
elements of a collection object in sequential manner without any need to know its
underlying representation.
Iterator pattern falls under behavioral pattern category.
Implementation
We're going to create a Iterator interface which narrates navigation method and a
Container interface which retruns the iterator . Concrete classes implementing the
Container interface will be responsible to implement Iterator interface and use it
[Link] 57/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create interfaces.
[Link]
public interface Iterator {
public boolean hasNext();
public Object next();
}
[Link]
public interface Container {
public Iterator getIterator();
}
Step 2
Create concrete class implementing the Container interface. This class has inner
class NameIterator implementing the Iterator interface.
[Link]
public class NameRepository implements Container {
public String names[] = {"Robert" , "John" ,"Julie" , "Lora"};
@Override
public Iterator getIterator() {
return new NameIterator();
}
private class NameIterator implements Iterator {
int index;
@Override
[Link] 58/110
10/14/2015 Design Pattern Quick Guide
public boolean hasNext() {
if(index < [Link]){
return true;
}
return false;
}
@Override
public Object next() {
if([Link]()){
return names[index++];
}
return null;
}
}
}
Step 3
Use the NameRepository to get iterator and print names.
[Link]
public class IteratorPatternDemo {
public static void main(String[] args) {
NameRepository namesRepository = new NameRepository();
for(Iterator iter = [Link](); [Link]();){
String name = (String)[Link]();
[Link]("Name : " + name);
}
}
}
Step 4
Verify the output.
Name : Robert
Name : John
Name : Julie
Name : Lora
Mediator Pattern
Mediator pattern is used to reduce communication complexity between multiple
objects or classes. This pattern provides a mediator class which normally handles
all the communications between different classes and supports easy maintainability
of the code by loose coupling. Mediator pattern falls under behavioral pattern
category.
[Link] 59/110
10/14/2015 Design Pattern Quick Guide
Implementation
We're demonstrating mediator pattern by example of a Chat Room where multiple
users can send message to Chat Room and it is the responsibility of Chat Room to
show the messages to all users. We've created two classes ChatRoom and User.
User objects will use ChatRoom method to share their messages.
MediatorPatternDemo, our demo class will use User objects to show
communication between them.
Step 1
Create mediator class.
[Link]
import [Link];
public class ChatRoom {
public static void showMessage(User user, String message){
[Link](new Date().toString()
+ " [" + [Link]() +"] : " + message);
}
}
Step 2
Create user class
[Link]
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public User(String name){
[Link] 60/110
10/14/2015 Design Pattern Quick Guide
[Link] = name;
}
public void sendMessage(String message){
[Link](this,message);
}
}
Step 3
Use the User object to show communications between them.
[Link]
public class MediatorPatternDemo {
public static void main(String[] args) {
User robert = new User("Robert");
User john = new User("John");
[Link]("Hi! John!");
[Link]("Hello! Robert!");
}
}
Step 4
Verify the output.
Thu Jan 31 [Link] IST 2013 [Robert] : Hi! John!
Thu Jan 31 [Link] IST 2013 [John] : Hello! Robert!
Memento Pattern
Memento pattern is used to reduce where we want to restore state of an object to
a previous state. Memento pattern falls under behavioral pattern category.
Implementation
Memento pattern uses three actor classes. Memento contains state of an object to
be restored. Originator creates and stores states in Memento objects and Caretaker
object which is responsible to restore object state from Memento. We've created
classes Memento, Originator and CareTaker.
MementoPatternDemo, our demo class will use CareTaker and Originator objects to
show restoration of object states.
[Link] 61/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create Memento class.
[Link]
public class Memento {
private String state;
public Memento(String state){
[Link] = state;
}
public String getState(){
return state;
}
}
Step 2
Create Originator class
[Link]
public class Originator {
private String state;
public void setState(String state){
[Link] = state;
}
public String getState(){
return state;
[Link] 62/110
10/14/2015 Design Pattern Quick Guide
}
public Memento saveStateToMemento(){
return new Memento(state);
}
public void getStateFromMemento(Memento Memento){
state = [Link]();
}
}
Step 3
Create CareTaker class
[Link]
import [Link];
import [Link];
public class CareTaker {
private List<Memento> mementoList = new ArrayList<Memento>();
public void add(Memento state){
[Link](state);
}
public Memento get(int index){
return [Link](index);
}
}
Step 4
Use CareTaker and Originator objects.
[Link]
public class MementoPatternDemo {
public static void main(String[] args) {
Originator originator = new Originator();
CareTaker careTaker = new CareTaker();
[Link]("State #1");
[Link]("State #2");
[Link]([Link]());
[Link]("State #3");
[Link]([Link]());
[Link]("State #4");
[Link]("Current State: " + [Link]());
[Link]([Link](0));
[Link]("First saved State: " + [Link]());
[Link]([Link](1));
[Link]("Second saved State: " + [Link]());
}
}
[Link] 63/110
10/14/2015 Design Pattern Quick Guide
Step 5
Verify the output.
Current State: State #4
First saved State: State #2
Second saved State: State #3
Observer Pattern
Observer pattern is used when there is one to many relationship between objects
such as if one object is modified, its depenedent objects are to be notified
automatically. Observer pattern falls under behavioral pattern category.
Implementation
Observer pattern uses three actor classes. Subject, Observer and Client. Subject,
an object having methods to attach and deattach observers to a client object.
We've created classes Subject, Observer abstract class and concrete classes
extending the abstract class the Observer.
ObserverPatternDemo, our demo class will use Subject and concrete class objects
to show observer pattern in action.
Step 1
[Link] 64/110
10/14/2015 Design Pattern Quick Guide
Create Subject class.
[Link]
import [Link];
import [Link];
public class Subject {
private List<Observer> observers
= new ArrayList<Observer>();
private int state;
public int getState() {
return state;
}
public void setState(int state) {
[Link] = state;
notifyAllObservers();
}
public void attach(Observer observer){
[Link](observer);
}
public void notifyAllObservers(){
for (Observer observer : observers) {
[Link]();
}
}
}
Step 2
Create Observer class.
[Link]
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
Step 3
Create concrete observer classes
[Link]
public class BinaryObserver extends Observer{
public BinaryObserver(Subject subject){
[Link] = subject;
[Link](this);
[Link] 65/110
10/14/2015 Design Pattern Quick Guide
}
@Override
public void update() {
[Link]( "Binary String: "
+ [Link]( [Link]() ) );
}
}
[Link]
public class OctalObserver extends Observer{
public OctalObserver(Subject subject){
[Link] = subject;
[Link](this);
}
@Override
public void update() {
[Link]( "Octal String: "
+ [Link]( [Link]() ) );
}
}
[Link]
public class HexaObserver extends Observer{
public HexaObserver(Subject subject){
[Link] = subject;
[Link](this);
}
@Override
public void update() {
[Link]( "Hex String: "
+ [Link]( [Link]() ).toUpperCase() );
}
}
Step 4
Use Subject and concrete observer objects.
[Link]
public class ObserverPatternDemo {
public static void main(String[] args) {
Subject subject = new Subject();
new HexaObserver(subject);
new OctalObserver(subject);
new BinaryObserver(subject);
[Link]("First state change: 15");
[Link](15);
[Link] 66/110
10/14/2015 Design Pattern Quick Guide
[Link]("Second state change: 10");
[Link](10);
}
}
Step 5
Verify the output.
First state change: 15
Hex String: F
Octal String: 17
Binary String: 1111
Second state change: 10
Hex String: A
Octal String: 12
Binary String: 1010
State Pattern
In State pattern a class behavior changes based on its state. This type of design
pattern comes under behavior pattern.
In State pattern, we create objects which represent various states and a context
object whose behavior varies as its state object changes.
Implementation
We're going to create a State interface defining a action and concrete state classes
implementing the State interface. Context is a class which carries a State.
StaePatternDemo, our demo class will use Context and state objects to
demonstrate change in Context behavior based on type of state it is in.
[Link] 67/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create an interface.
[Link]
public interface State {
public void doAction(Context context);
}
Step 2
Create concrete classes implementing the same interface.
[Link]
public class StartState implements State {
public void doAction(Context context) {
[Link]("Player is in start state");
[Link](this);
}
public String toString(){
return "Start State";
}
}
[Link]
[Link] 68/110
10/14/2015 Design Pattern Quick Guide
public class StopState implements State {
public void doAction(Context context) {
[Link]("Player is in stop state");
[Link](this);
}
public String toString(){
return "Stop State";
}
}
Step 3
Create Context Class.
[Link]
public class Context {
private State state;
public Context(){
state = null;
}
public void setState(State state){
[Link] = state;
}
public State getState(){
return state;
}
}
Step 4
Use the Context to see change in behaviour when State changes.
[Link]
public class StatePatternDemo {
public static void main(String[] args) {
Context context = new Context();
StartState startState = new StartState();
[Link](context);
[Link]([Link]().toString());
StopState stopState = new StopState();
[Link](context);
[Link]([Link]().toString());
}
}
[Link] 69/110
10/14/2015 Design Pattern Quick Guide
Step 5
Verify the output.
Player is in start state
Start State
Player is in stop state
Stop State
Null Object Pattern
In Null Object pattern, a null object replaces check of NULL object instance. Instead
of putting if check for a null value, Null Object reflects a do nothing relationship.
Such Null object can also be used to provide default behaviour in case data is not
available.
In Null Object pattern, we create a abstract class specifying the various operations
to be done, concreate classes extending this class and a null object class providing
do nothing implemention of this class and will be used seemlessly where we need
to check null value.
Implementation
We're going to create a AbstractCustomer abstract class defining opearations, here
the name of the customer and concrete classes extending the AbstractCustomer
class. A factory class CustomerFactory is created to return either RealCustomer or
NullCustomer objects based on the name of customer passed to it.
NullPatternDemo, our demo class will use CustomerFactory to demonstrate use of
Null Object pattern.
[Link] 70/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create an abstract class.
[Link]
public abstract class AbstractCustomer {
protected String name;
public abstract boolean isNil();
public abstract String getName();
}
Step 2
Create concrete classes extending the above class.
[Link]
public class RealCustomer extends AbstractCustomer {
public RealCustomer(String name) {
[Link] = name;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isNil() {
return false;
}
}
[Link]
[Link] 71/110
10/14/2015 Design Pattern Quick Guide
public class NullCustomer extends AbstractCustomer {
@Override
public String getName() {
return "Not Available in Customer Database";
}
@Override
public boolean isNil() {
return true;
}
}
Step 3
Create CustomerFactory Class.
[Link]
public class CustomerFactory {
public static final String[] names = {"Rob", "Joe", "Julie"};
public static AbstractCustomer getCustomer(String name){
for (int i = 0; i < [Link]; i++) {
if (names[i].equalsIgnoreCase(name)){
return new RealCustomer(name);
}
}
return new NullCustomer();
}
}
Step 4
Use the CustomerFactory get either RealCustomer or NullCustomer objects based
on the name of customer passed to it.
[Link]
public class NullPatternDemo {
public static void main(String[] args) {
AbstractCustomer customer1 = [Link]("Rob");
AbstractCustomer customer2 = [Link]("Bob");
AbstractCustomer customer3 = [Link]("Julie");
AbstractCustomer customer4 = [Link]("Laura");
[Link]("Customers");
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}
[Link] 72/110
10/14/2015 Design Pattern Quick Guide
Step 5
Verify the output.
Customers
Rob
Not Available in Customer Database
Julie
Not Available in Customer Database
Strategy Pattern
In Strategy pattern, a class behavior or its algorithm can be changed at run time.
This type of design pattern comes under behavior pattern.
In Strategy pattern, we create objects which represent various strategies and a
context object whose behavior varies as per its strategy object. The strategy object
changes the executing algorithm of the context object.
Implementation
We're going to create a Strategy interface defining a action and concrete strategy
classes implementing the Strategy interface. Context is a class which uses a
Strategy.
StrategyPatternDemo, our demo class will use Context and strategy objects to
demonstrate change in Context behaviour based on strategy it deploys or uses.
[Link] 73/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create an interface.
[Link]
public interface Strategy {
public int doOperation(int num1, int num2);
}
Step 2
Create concrete classes implementing the same interface.
[Link]
public class OperationAdd implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
[Link]
public class OperationSubstract implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 ‐ num2;
}
}
[Link]
public class OperationMultiply implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
Step 3
Create Context Class.
[Link]
public class Context {
private Strategy strategy;
public Context(Strategy strategy){
[Link] = strategy;
[Link] 74/110
10/14/2015 Design Pattern Quick Guide
}
public int executeStrategy(int num1, int num2){
return [Link](num1, num2);
}
}
Step 4
Use the Context to see change in behaviour when it changes its Strategy.
[Link]
public class StrategyPatternDemo {
public static void main(String[] args) {
Context context = new Context(new OperationAdd());
[Link]("10 + 5 = " + [Link](10, 5));
context = new Context(new OperationSubstract());
[Link]("10 ‐ 5 = " + [Link](10, 5));
context = new Context(new OperationMultiply());
[Link]("10 * 5 = " + [Link](10, 5));
}
}
Step 5
Verify the output.
10 + 5 = 15
10 ‐ 5 = 5
10 * 5 = 50
Template Pattern
In Template pattern, an abstract class exposes defined way(s)/template(s) to
execute its methods. Its subclasses can overrides the method implementations as
per need basis but the invocation is to be in the same way as defined by an
abstract class. This pattern comes under behavior pattern category.
Implementation
We're going to create a Game abstract class defining operations with a template
method set to be final so that it cannot be overridden. Cricket and Football are
concrete classes extend Game and override its methods.
TemplatePatternDemo, our demo class will use Game to demonstrate use of
template pattern.
[Link] 75/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create an abstract class with a template method being final.
[Link]
public abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
//template method
public final void play(){
//initialize the game
initialize();
//start game
startPlay();
//end game
endPlay();
}
}
Step 2
Create concrete classes extending the above class.
[Link]
public class Cricket extends Game {
[Link] 76/110
10/14/2015 Design Pattern Quick Guide
@Override
void endPlay() {
[Link]("Cricket Game Finished!");
}
@Override
void initialize() {
[Link]("Cricket Game Initialized! Start playing.");
}
@Override
void startPlay() {
[Link]("Cricket Game Started. Enjoy the game!");
}
}
[Link]
public class Football extends Game {
@Override
void endPlay() {
[Link]("Football Game Finished!");
}
@Override
void initialize() {
[Link]("Football Game Initialized! Start playing.");
}
@Override
void startPlay() {
[Link]("Football Game Started. Enjoy the game!");
}
}
Step 3
Use the Game's template method play() to demonstrate a defined way of playing
game.
[Link]
public class TemplatePatternDemo {
public static void main(String[] args) {
Game game = new Cricket();
[Link]();
[Link]();
game = new Football();
[Link]();
}
}
Step 4
[Link] 77/110
10/14/2015 Design Pattern Quick Guide
Verify the output.
Cricket Game Initialized! Start playing.
Cricket Game Started. Enjoy the game!
Cricket Game Finished!
Football Game Initialized! Start playing.
Football Game Started. Enjoy the game!
Football Game Finished!
Visitor Pattern
In Visitor pattern, we use a visitor class which changes the executing algorithm of
an element class. By this way, execution algorithm of element can varies as visitor
varies. This pattern comes under behavior pattern category. As per the pattern,
element object has to accept the visitor object so that visitor object handles the
operation on the element object.
Implementation
We're going to create a ComputerPart interface defining accept
[Link], Mouse, Monitor and Computer are concrete classes
implementing ComputerPart interface. We'll define another interface
ComputerPartVisitor which will define a visitor class operations. Computer uses
concrete visitor to do corresponding action.
VisitorPatternDemo, our demo class will use Computer, ComputerPartVisitor classes
to demonstrate use of visitor pattern.
[Link] 78/110
10/14/2015 Design Pattern Quick Guide
Step 1
Define an interface to represent element.
[Link]
public interface class ComputerPart {
public void accept(ComputerPartVisitor computerPartVisitor);
}
Step 2
Create concrete classes extending the above class.
[Link]
public class Keyboard implements ComputerPart {
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
[Link](this);
}
}
[Link]
public class Monitor implements ComputerPart {
@Override
[Link] 79/110
10/14/2015 Design Pattern Quick Guide
public void accept(ComputerPartVisitor computerPartVisitor) {
[Link](this);
}
}
[Link]
public class Mouse implements ComputerPart {
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
[Link](this);
}
}
[Link]
public class Computer implements ComputerPart {
ComputerPart[] parts;
public Computer(){
parts = new ComputerPart[] {new Mouse(), new Keyboard(), new Monitor()};
}
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
for (int i = 0; i < [Link]; i++) {
parts[i].accept(computerPartVisitor);
}
[Link](this);
}
}
Step 3
Define an interface to represent visitor.
[Link]
public interface ComputerPartVisitor {
public void visit(Computer computer);
public void visit(Mouse mouse);
public void visit(Keyboard keyboard);
public void visit(Monitor monitor);
}
Step 4
Create concrete visitor implementing the above class.
[Link]
[Link] 80/110
10/14/2015 Design Pattern Quick Guide
public class ComputerPartDisplayVisitor implements ComputerPartVisitor {
@Override
public void visit(Computer computer) {
[Link]("Displaying Computer.");
}
@Override
public void visit(Mouse mouse) {
[Link]("Displaying Mouse.");
}
@Override
public void visit(Keyboard keyboard) {
[Link]("Displaying Keyboard.");
}
@Override
public void visit(Monitor monitor) {
[Link]("Displaying Monitor.");
}
}
Step 5
Use the ComputerPartDisplayVisitor to display parts of Computer.
[Link]
public class VisitorPatternDemo {
public static void main(String[] args) {
ComputerPart computer = new Computer();
[Link](new ComputerPartDisplayVisitor());
}
}
Step 6
Verify the output.
Displaying Mouse.
Displaying Keyboard.
Displaying Monitor.
Displaying Computer.
MVC Pattern
MVC Pattern stands for ModelViewController Pattern. This pattern is used to
separate application's concerns.
Model Model represents an object or JAVA POJO carrying data. It can also
[Link] 81/110
10/14/2015 Design Pattern Quick Guide
have logic to update controller if its data changes.
View View represents the visualization of the data that model contains.
Controller Controller acts on both Model and view. It controls the data
flow into model object and updates the view whenever data changes. It
keeps View and Model separate.
Implementation
We're going to create a Student object acting as a [Link] will be a
view class which can print student details on console and StudentController is the
controller class responsible to store data in Student object and update view
StudentView accordingly.
MVCPatternDemo, our demo class will use StudentController to demonstrate use of
MVC pattern.
Step 1
Create Model.
[Link]
public class Student {
private String rollNo;
[Link] 82/110
10/14/2015 Design Pattern Quick Guide
private String name;
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
[Link] = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
}
Step 2
Create View.
[Link]
public class StudentView {
public void printStudentDetails(String studentName, String studentRollNo){
[Link]("Student: ");
[Link]("Name: " + studentName);
[Link]("Roll No: " + studentRollNo);
}
}
Step 3
Create Controller.
[Link]
public class StudentController {
private Student model;
private StudentView view;
public StudentController(Student model, StudentView view){
[Link] = model;
[Link] = view;
}
public void setStudentName(String name){
[Link](name);
}
public String getStudentName(){
return [Link]();
}
public void setStudentRollNo(String rollNo){
[Link](rollNo);
}
[Link] 83/110
10/14/2015 Design Pattern Quick Guide
public String getStudentRollNo(){
return [Link]();
}
public void updateView(){
[Link]([Link](), [Link]());
}
}
Step 4
Use the StudentController methods to demonstrate MVC design pattern usage.
[Link]
public class MVCPatternDemo {
public static void main(String[] args) {
//fetch student record based on his roll no from the database
Student model = retriveStudentFromDatabase();
//Create a view : to write student details on console
StudentView view = new StudentView();
StudentController controller = new StudentController(model, view);
[Link]();
//update model data
[Link]("John");
[Link]();
}
private static Student retriveStudentFromDatabase(){
Student student = new Student();
[Link]("Robert");
[Link]("10");
return student;
}
}
Step 5
Verify the output.
Student:
Name: Robert
Roll No: 10
Student:
Name: Julie
Roll No: 10
Business Delegate Pattern
[Link] 84/110
10/14/2015 Design Pattern Quick Guide
Business Delegate Pattern
Business Delegate Pattern is used to decouple presentation tier and business tier. It
is basically use to reduce communication or remote lookup functionality to business
tier code in presentation tier code. In business tier we've following entities.
Client Presentation tier code may be JSP, servlet or UI java code.
LookUp Service Lookup service object is responsible to get relative
business implementation and provide business object access to business
delegate object.
Implementation
We're going to create a Client, BusinessDelegate, BusinessService, LookUpService,
JMSService and EJBService representing various entities of Business Delegate
pattern.
[Link] 85/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create BusinessService Interface.
[Link]
public interface BusinessService {
public void doProcessing();
}
Step 2
Create Concreate Service Classes.
[Link]
public class EJBService implements BusinessService {
@Override
public void doProcessing() {
[Link]("Processing task by invoking EJB Service");
}
}
[Link]
public class JMSService implements BusinessService {
@Override
[Link] 86/110
10/14/2015 Design Pattern Quick Guide
public void doProcessing() {
[Link]("Processing task by invoking JMS Service");
}
}
Step 3
Create Business Lookup Service.
[Link]
public class BusinessLookUp {
public BusinessService getBusinessService(String serviceType){
if([Link]("EJB")){
return new EJBService();
}else {
return new JMSService();
}
}
}
Step 4
Create Business Delegate.
[Link]
public class BusinessDelegate {
private BusinessLookUp lookupService = new BusinessLookUp();
private BusinessService businessService;
private String serviceType;
public void setServiceType(String serviceType){
[Link] = serviceType;
}
public void doTask(){
businessService = [Link](serviceType);
[Link]();
}
}
Step 5
Create Client.
[Link]
public class Client {
BusinessDelegate businessService;
public Client(BusinessDelegate businessService){
[Link] 87/110
10/14/2015 Design Pattern Quick Guide
[Link] = businessService;
}
public void doTask(){
[Link]();
}
}
Step 6
Use BusinessDelegate and Client classes to demonstrate Business Delegate
pattern.
[Link]
public class BusinessDelegatePatternDemo {
public static void main(String[] args) {
BusinessDelegate businessDelegate = new BusinessDelegate();
[Link]("EJB");
Client client = new Client(businessDelegate);
[Link]();
[Link]("JMS");
[Link]();
}
}
Step 7
Verify the output.
Processing task by invoking EJB Service
Processing task by invoking JMS Service
Composite Entity Pattern
Composite Entity pattern is used in EJB persistence mechanism. A Composite entity
is an EJB entity bean which represents a graph of objects. When a composite entity
is updated, internally dependent objects beans get updated automatically as being
managed by EJB entity bean. Following are the participants in Composite Entity
Bean.
Composite Entity It is primary entity [Link] can be coarse grained or
can contain a coarse grained object to be used for persistence purpose.
Strategies Strategies represents how to implement a Composite Entity.
Implementation
We're going to create CompositeEntity object acting as CompositeEntity.
CoarseGrainedObject will be a class which contains dependent objects.
CompositeEntityPatternDemo, our demo class will use Client class to demonstrate
use of Composite Entity pattern.
Step 1
Create Dependent Objects.
[Link]
public class DependentObject1 {
private String data;
public void setData(String data){
[Link] = data;
}
public String getData(){
return data;
[Link] 89/110
10/14/2015 Design Pattern Quick Guide
}
}
[Link]
public class DependentObject2 {
private String data;
public void setData(String data){
[Link] = data;
}
public String getData(){
return data;
}
}
Step 2
Create Coarse Grained Object.
[Link]
public class CoarseGrainedObject {
DependentObject1 do1 = new DependentObject1();
DependentObject2 do2 = new DependentObject2();
public void setData(String data1, String data2){
[Link](data1);
[Link](data2);
}
public String[] getData(){
return new String[] {[Link](),[Link]()};
}
}
Step 3
Create Composite Entity.
[Link]
public class CompositeEntity {
private CoarseGrainedObject cgo = new CoarseGrainedObject();
public void setData(String data1, String data2){
[Link](data1, data2);
}
public String[] getData(){
return [Link]();
}
}
[Link] 90/110
10/14/2015 Design Pattern Quick Guide
Step 4
Create Client class to use Composite Entity.
[Link]
public class Client {
private CompositeEntity compositeEntity = new CompositeEntity();
public void printData(){
for (int i = 0; i < [Link]().length; i++) {
[Link]("Data: " + [Link]()[i]);
}
}
public void setData(String data1, String data2){
[Link](data1, data2);
}
}
Step 5
Use the Client to demonstrate Composite Entity design pattern usage.
[Link]
public class CompositeEntityPatternDemo {
public static void main(String[] args) {
Client client = new Client();
[Link]("Test", "Data");
[Link]();
[Link]("Second Test", "Data1");
[Link]();
}
}
Step 6
Verify the output.
Data: Test
Data: Data
Data: Second Test
Data: Data1
Data Access Object Pattern
Data Access Object Pattern or DAO pattern is used to separate low level data
accessing API or operations from high level business services. Following are the
participants in Data Access Object Pattern.
[Link] 91/110
10/14/2015 Design Pattern Quick Guide
Model Object or Value Object This object is simple POJO containing
get/set methods to store data retrieved using DAO class.
Implementation
We're going to create a Student object acting as a Model or Value
[Link] is Data Access Object [Link] is concrete
class implementing Data Access Object Interface. DaoPatternDemo, our demo
class will use StudentDao demonstrate use of Data Access Object pattern.
Step 1
Create Value Object.
[Link]
public class Student {
private String name;
private int rollNo;
[Link] 92/110
10/14/2015 Design Pattern Quick Guide
Student(String name, int rollNo){
[Link] = name;
[Link] = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
[Link] = rollNo;
}
}
Step 2
Create Data Access Object Interface.
[Link]
import [Link];
public interface StudentDao {
public List<Student> getAllStudents();
public Student getStudent(int rollNo);
public void updateStudent(Student student);
public void deleteStudent(Student student);
}
Step 3
Create concreate class implementing above interface.
[Link]
import [Link];
import [Link];
public class StudentDaoImpl implements StudentDao {
//list is working as a database
List<Student> students;
public StudentDaoImpl(){
students = new ArrayList<Student>();
Student student1 = new Student("Robert",0);
Student student2 = new Student("John",1);
[Link](student1);
[Link] 93/110
10/14/2015 Design Pattern Quick Guide
[Link](student2);
}
@Override
public void deleteStudent(Student student) {
[Link]([Link]());
[Link]("Student: Roll No " + [Link]()
+", deleted from database");
}
//retrive list of students from the database
@Override
public List<Student> getAllStudents() {
return students;
}
@Override
public Student getStudent(int rollNo) {
return [Link](rollNo);
}
@Override
public void updateStudent(Student student) {
[Link]([Link]()).setName([Link]());
[Link]("Student: Roll No " + [Link]()
+", updated in the database");
}
}
Step 4
Use the StudentDao to demonstrate Data Access Object pattern usage.
[Link]
public class DaoPatternDemo {
public static void main(String[] args) {
StudentDao studentDao = new StudentDaoImpl();
//print all students
for (Student student : [Link]()) {
[Link]("Student: [RollNo : "
+[Link]()+", Name : "+[Link]()+" ]");
}
//update student
Student student =[Link]().get(0);
[Link]("Michael");
[Link](student);
//get the student
[Link](0);
[Link]("Student: [RollNo : "
+[Link]()+", Name : "+[Link]()+" ]");
}
}
[Link] 94/110
10/14/2015 Design Pattern Quick Guide
Step 5
Verify the output.
Student: [RollNo : 0, Name : Robert ]
Student: [RollNo : 1, Name : John ]
Student: Roll No 0, updated in the database
Student: [RollNo : 0, Name : Michael ]
Front Controller Pattern
The front controller design pattern is used to provide a centralized request handling
mechanism so that all requests will be handled by a single handler. This handler can
do the authentication/ authorization/ logging or tracking of request and then pass
the requests to corresponding handlers. Following are the entities of this type of
design pattern.
Front Controller Single handler for all kind of request coming to the
application (either web based/ desktop based).
View Views are the object for which the requests are made.
Implementation
We're going to create a FrontController,Dispatcher to act as Front Controller and
Dispatcher correspondingly. HomeView and StudentView represent various views
for which requests can come to front controller.
[Link] 95/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create Views.
[Link]
public class HomeView {
public void show(){
[Link]("Displaying Home Page");
}
}
[Link]
public class StudentView {
public void show(){
[Link]("Displaying Student Page");
}
}
Step 2
Create Dispatcher.
[Link]
public class Dispatcher {
private StudentView studentView;
private HomeView homeView;
public Dispatcher(){
studentView = new StudentView();
homeView = new HomeView();
}
public void dispatch(String request){
if([Link]("STUDENT")){
[Link]();
[Link] 96/110
10/14/2015 Design Pattern Quick Guide
}else{
[Link]();
}
}
}
Step 3
Create FrontController
[Link]
public class FrontController {
private Dispatcher dispatcher;
public FrontController(){
dispatcher = new Dispatcher();
}
private boolean isAuthenticUser(){
[Link]("User is authenticated successfully.");
return true;
}
private void trackRequest(String request){
[Link]("Page requested: " + request);
}
public void dispatchRequest(String request){
//log each request
trackRequest(request);
//authenticate the user
if(isAuthenticUser()){
[Link](request);
}
}
}
Step 4
Use the FrontController to demonstrate Front Controller Design Pattern.
[Link]
public class FrontControllerPatternDemo {
public static void main(String[] args) {
FrontController frontController = new FrontController();
[Link]("HOME");
[Link]("STUDENT");
}
}
Step 5
[Link] 97/110
10/14/2015 Design Pattern Quick Guide
Verify the output.
Page requested: HOME
User is authenticated successfully.
Displaying Home Page
Page requested: STUDENT
User is authenticated successfully.
Displaying Student Page
Intercepting Filter Pattern
The intercepting filter design pattern is used when we want to do some pre
processing / postprocessing with request or response of the application. Filters are
defined and applied on the request before passing the request to actual target
application. Filters can do the authentication/ authorization/ logging or tracking of
request and then pass the requests to corresponding handlers. Following are the
entities of this type of design pattern.
Filter Filter which will perform certain task prior or after execution of
request by request handler.
Filter Chain Filter Chain carries multiple filters and help to execute them
in defined order on target.
Target Target object is the request handler
Filter Manager Filter Manager manages the filters and Filter Chain.
Client Client is the object who sends request to the Target object.
Implementation
We're going to create a FilterChain,FilterManager, Target, Client as various objects
representing our [Link] and DebugFilter represents concrete
filters.
InterceptingFilterDemo, our demo class will use Client to demonstrate Intercepting
Filter Design Pattern.
[Link] 98/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create Filter interface.
[Link]
public interface Filter {
public void execute(String request);
}
Step 2
Create concrete filters.
[Link]
public class AuthenticationFilter implements Filter {
public void execute(String request){
[Link]("Authenticating request: " + request);
}
}
[Link]
public class DebugFilter implements Filter {
public void execute(String request){
[Link]("request log: " + request);
[Link] 99/110
10/14/2015 Design Pattern Quick Guide
}
}
Step 3
Create Target
[Link]
public class Target {
public void execute(String request){
[Link]("Executing request: " + request);
}
}
Step 4
Create Filter Chain
[Link]
import [Link];
import [Link];
public class FilterChain {
private List<Filter> filters = new ArrayList<Filter>();
private Target target;
public void addFilter(Filter filter){
[Link](filter);
}
public void execute(String request){
for (Filter filter : filters) {
[Link](request);
}
[Link](request);
}
public void setTarget(Target target){
[Link] = target;
}
}
Step 5
Create Filter Manager
[Link]
public class FilterManager {
FilterChain filterChain;
[Link] 100/110
10/14/2015 Design Pattern Quick Guide
public FilterManager(Target target){
filterChain = new FilterChain();
[Link](target);
}
public void setFilter(Filter filter){
[Link](filter);
}
public void filterRequest(String request){
[Link](request);
}
}
Step 6
Create Client
[Link]
public class Client {
FilterManager filterManager;
public void setFilterManager(FilterManager filterManager){
[Link] = filterManager;
}
public void sendRequest(String request){
[Link](request);
}
}
Step 7
Use the Client to demonstrate Intercepting Filter Design Pattern.
[Link]
public class InterceptingFilterDemo {
public static void main(String[] args) {
FilterManager filterManager = new FilterManager(new Target());
[Link](new AuthenticationFilter());
[Link](new DebugFilter());
Client client = new Client();
[Link](filterManager);
[Link]("HOME");
}
}
Step 8
Verify the output.
[Link] 101/110
10/14/2015 Design Pattern Quick Guide
Authenticating request: HOME
request log: HOME
Executing request: HOME
Service Locator Pattern
The service locator design pattern is used when we want to locate various services
using JNDI lookup. Considering high cost of looking up JNDI for a service, Service
Locator pattern makes use of caching technique. For the first time a service is
required, Service Locator looks up in JNDI and caches the service object. Further
lookup or same service via Service Locator is done in its cache which improves the
performance of application to great extent. Following are the entities of this type of
design pattern.
Service Actual Service which will process the request. Reference of such
service is to be looked upon in JNDI server.
Context / Initial Context JNDI Context, carries the reference to service
used for lookup purpose.
Service Locator Service Locator is a single point of contact to get
services by JNDI lookup, caching the services.
Cache Cache to store references of services to reuse them
Client Client is the object who invokes the services via ServiceLocator.
Implementation
We're going to create a ServiceLocator,InitialContext, Cache, Service as various
objects representing our entities.Service1 and Service2 represents concrete
services.
ServiceLocatorPatternDemo, our demo class is acting as a client here and will use
ServiceLocator to demonstrate Service Locator Design Pattern.
[Link] 102/110
10/14/2015 Design Pattern Quick Guide
Step 1
Create Service interface.
[Link]
public interface Service {
public String getName();
public void execute();
}
Step 2
Create concrete services.
[Link]
public class Service1 implements Service {
public void execute(){
[Link]("Executing Service1");
}
@Override
public String getName() {
return "Service1";
}
[Link] 103/110
10/14/2015 Design Pattern Quick Guide
[Link]
public class Service2 implements Service {
public void execute(){
[Link]("Executing Service2");
}
@Override
public String getName() {
return "Service2";
}
}
Step 3
Create InitialContext for JNDI lookup
[Link]
public class InitialContext {
public Object lookup(String jndiName){
if([Link]("SERVICE1")){
[Link]("Looking up and creating a new Service1 object");
return new Service1();
}else if ([Link]("SERVICE2")){
[Link]("Looking up and creating a new Service2 object");
return new Service2();
}
return null;
}
}
Step 4
Create Cache
[Link]
import [Link];
import [Link];
public class Cache {
private List<Service> services;
public Cache(){
services = new ArrayList<Service>();
}
public Service getService(String serviceName){
for (Service service : services) {
if([Link]().equalsIgnoreCase(serviceName)){
[Link]("Returning cached "+serviceName+" object");
[Link] 104/110
10/14/2015 Design Pattern Quick Guide
return service;
}
}
return null;
}
public void addService(Service newService){
boolean exists = false;
for (Service service : services) {
if([Link]().equalsIgnoreCase([Link]())){
exists = true;
}
}
if(!exists){
[Link](newService);
}
}
}
Step 5
Create Service Locator
[Link]
public class ServiceLocator {
private static Cache cache;
static {
cache = new Cache();
}
public static Service getService(String jndiName){
Service service = [Link](jndiName);
if(service != null){
return service;
}
InitialContext context = new InitialContext();
Service service1 = (Service)[Link](jndiName);
[Link](service1);
return service1;
}
}
Step 6
Use the ServiceLocator to demonstrate Service Locator Design Pattern.
[Link]
public class ServiceLocatorPatternDemo {
public static void main(String[] args) {
Service service = [Link]("Service1");
[Link] 105/110
10/14/2015 Design Pattern Quick Guide
[Link]();
service = [Link]("Service2");
[Link]();
service = [Link]("Service1");
[Link]();
service = [Link]("Service2");
[Link]();
}
}
Step 7
Verify the output.
Looking up and creating a new Service1 object
Executing Service1
Looking up and creating a new Service2 object
Executing Service2
Returning cached Service1 object
Executing Service1
Returning cached Service2 object
Executing Service2
Transfer Object Pattern
The Transfer Object pattern is used when we want to pass data with multiple
attributes in one shot from client to server. Transfer object is also known as Value
Object. Transfer Object is a simple POJO class having getter/setter methods and is
serializable so that it can be transferred over the network. It do not have any
behavior. Server Side business class normally fetches data from the database and
fills the POJO and send it to the client or pass it by value. For client, transfer object
is readonly. Client can create its own transfer object and pass it to server to
update values in database in one shot. Following are the entities of this type of
design pattern.
Business Object Business Service which fills the Transfer Object with
data.
Transfer Object Simple POJO, having methods to set/get attributes only.
Client Client either requests or sends the Transfer Object to Business
Object.
Implementation
We're going to create a StudentBO as Business Object,Student as Transfer Object
[Link] 106/110
10/14/2015 Design Pattern Quick Guide
representing our entities.
TransferObjectPatternDemo, our demo class is acting as a client here and will use
StudentBO and Student to demonstrate Transfer Object Design Pattern.
Step 1
Create Transfer Object.
[Link]
public class StudentVO {
private String name;
private int rollNo;
StudentVO(String name, int rollNo){
[Link] = name;
[Link] = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
[Link] = rollNo;
[Link] 107/110
10/14/2015 Design Pattern Quick Guide
}
}
Step 2
Create Business Object.
[Link]
import [Link];
import [Link];
public class StudentBO {
//list is working as a database
List<StudentVO> students;
public StudentBO(){
students = new ArrayList<StudentVO>();
StudentVO student1 = new StudentVO("Robert",0);
StudentVO student2 = new StudentVO("John",1);
[Link](student1);
[Link](student2);
}
public void deleteStudent(StudentVO student) {
[Link]([Link]());
[Link]("Student: Roll No "
+ [Link]() +", deleted from database");
}
//retrive list of students from the database
public List<StudentVO> getAllStudents() {
return students;
}
public StudentVO getStudent(int rollNo) {
return [Link](rollNo);
}
public void updateStudent(StudentVO student) {
[Link]([Link]()).setName([Link]());
[Link]("Student: Roll No "
+ [Link]() +", updated in the database");
}
}
Step 3
Use the StudentBO to demonstrate Transfer Object Design Pattern.
[Link]
public class TransferObjectPatternDemo {
public static void main(String[] args) {
StudentBO studentBusinessObject = new StudentBO();
[Link] 108/110
10/14/2015 Design Pattern Quick Guide
//print all students
for (StudentVO student : [Link]()) {
[Link]("Student: [RollNo : "
+[Link]()+", Name : "+[Link]()+" ]");
}
//update student
StudentVO student =[Link]().get(0);
[Link]("Michael");
[Link](student);
//get the student
[Link](0);
[Link]("Student: [RollNo : "
+[Link]()+", Name : "+[Link]()+" ]");
}
}
Step 4
Verify the output.
Student: [RollNo : 0, Name : Robert ]
Student: [RollNo : 1, Name : John ]
Student: Roll No 0, updated in the database
Student: [RollNo : 0, Name : Michael ]
Previous Page Next Page
Advertisements
[Link] 109/110
10/14/2015 Design Pattern Quick Guide
[Link] 110/110