Design Pattern Tutorial
Design Pattern Tutorial
Audience
This reference has been prepared for the experienced developers to provide best
solutions to certain problems faced during software development and for unexperienced developers to learn software design in an easy and faster way.
Prerequisites
Before you start proceeding with this tutorial, we make an assumption that you
are already aware of the basic concepts of Java programming.
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
Copyright & Disclaimer............................................................................................................................. i
Table of Contents .................................................................................................................................... ii
1.
2.
3.
4.
5.
6.
7.
8.
BRIDGE PATTERN............................................................................................................... 38
Implementation .................................................................................................................................... 38
ii
9.
iii
iv
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 help unexperienced developers to learn software design in an easy
and fast way.
Creational Patterns
These design patterns provide a way to create objects while hiding the
creation logic, rather than instantiating objects directly using new
operator. This gives more flexibility to the program 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
inheritance is used to compose interfaces and define ways to compose
objects to obtain new functionalities.
Behavioral Patterns
These design patterns are specifically concerned with communication
between objects.
J2EE Patterns
These design patterns are specifically concerned with the presentation
tier. These patterns are identified by Sun Java Center.
2. FACTORY PATTERN
Factory pattern is one of most used design patterns 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 objects without exposing the creation logic to the
client and refer to newly created object using a common interface.
Implementation
We are 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.
Shape.java
public interface Shape {
void draw();
3
Step 2
Create concrete classes implementing the same interface.
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
Step 3
Create a Factory to generate object of concrete class based on given information.
ShapeFactory.java
public class ShapeFactory {
Step 4
Use the Factory to get object of concrete class by passing an information such as
type.
FactoryPatternDemo.java
public class FactoryPatternDemo {
Step 5
Verify the output.
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.
Implementation
We are going to create a Shape and Color interfaces and concrete classes
implementing these interfaces. We create an abstract factory class
AbstractFactory as next step. Factory classes ShapeFactory and ColorFactory are
defined where each factory extends AbstractFactory. A factory creator/generator
class FactoryProducer is created.
AbstractFactoryPatternDemo, our demo class, uses FactoryProducer to get an
AbstractFactory object. It will pass information (CIRCLE / RECTANGLE / SQUARE
for Shape) to AbstractFactory to get the type of object it needs. It also passes
information (RED / GREEN / BLUE for Color) to AbstractFactory to get the type of
object it needs.
Step 1
Create an interface for Shapes.
Shape.java
public interface Shape {
void draw();
}
Step 2
Create concrete classes implementing the same interface.
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
8
}
}
Square.java
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
Step 3
Create an interface for Colors.
Color.java
public interface Color {
void fill();
}
Step4
Create concrete classes implementing the same interface.
Red.java
public class Red implements Color {
@Override
public void fill() {
System.out.println("Inside Red::fill() method.");
}
}
Green.java
public class Green implements Color {
@Override
public void fill() {
System.out.println("Inside Green::fill() method.");
}
}
Blue.java
public class Blue implements Color {
@Override
public void fill() {
System.out.println("Inside Blue::fill() method.");
}
}
Step 5
Create an Abstract class to get factories for Color and Shape Objects.
AbstractFactory.java
public abstract class AbstractFactory {
abstract Color getColor(String color);
10
Step 6
Create Factory classes extending AbstractFactory to generate object of concrete
class based on given information.
ShapeFactory.java
public class ShapeFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
@Override
Color getColor(String color) {
return null;
}
}
11
ColorFactory.java
public class ColorFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
return null;
}
@Override
Color getColor(String color) {
if(color == null){
return null;
}
if(color.equalsIgnoreCase("RED")){
return new Red();
} else if(color.equalsIgnoreCase("GREEN")){
return new Green();
} else if(color.equalsIgnoreCase("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
FactoryProducer.java
public class FactoryProducer {
public static AbstractFactory getFactory(String choice){
if(choice.equalsIgnoreCase("SHAPE")){
return new ShapeFactory();
} else if(choice.equalsIgnoreCase("COLOR")){
12
Step 8
Use the FactoryProducer to get AbstractFactory in order to get factories of concrete
classes by passing an information such as type.
AbstractFactoryPatternDemo.java
public class AbstractFactoryPatternDemo {
public static void main(String[] args) {
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.
Inside Blue::fill() method.
14
4. 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
ways to create an object.
This pattern involves a single class which is responsible to create an object while
making sure that only single object gets created. This class provides a way to
access its only object which can be accessed directly without instantiating the
object of the class.
Implementation
We are going to create a SingleObject class which has its constructor as private
and 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.
15
Step 1
Create a Singleton Class.
SingleObject.java
public class SingleObject {
Step 2
Get the only object from the singleton class.
SingletonPatternDemo.java
public class SingletonPatternDemo {
public static void main(String[] args) {
//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();
16
Step 3
Verify the output.
Hello World!
17
5. 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.
A Builder class builds the final object step by step. This builder is independent of
other objects.
Implementation
We have considered a business case of fast-food 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 are 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 objects by combining Item. BuilderPatternDemo, our demo
class, will use MealBuilder to build a Meal.
18
Step 1
Create an interface Item representing food item and packing.
Item.java
public interface Item {
public String name();
public Packing packing();
public float price();
}
Packing.java
public interface Packing {
public String pack();
}
19
Step 2
Create concrete classes implementing the Packing interface.
Wrapper.java
public class Wrapper implements Packing {
@Override
public String pack() {
return "Wrapper";
}
}
Bottle.java
public class Bottle implements Packing {
@Override
public String pack() {
return "Bottle";
}
}
Step 3
Create abstract classes implementing the item interface providing default
functionalities.
Burger.java
public abstract class Burger implements Item {
@Override
public Packing packing() {
return new Wrapper();
}
@Override
20
ColdDrink.java
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
VegBurger.java
public class VegBurger extends Burger {
@Override
public float price() {
return 25.0f;
}
@Override
public String name() {
return "Veg Burger";
}
}
21
ChickenBurger.java
public class ChickenBurger extends Burger {
@Override
public float price() {
return 50.5f;
}
@Override
public String name() {
return "Chicken Burger";
}
}
Coke.java
public class Coke extends ColdDrink {
@Override
public float price() {
return 30.0f;
}
@Override
public String name() {
return "Coke";
}
}
Pepsi.java
public class Pepsi extends ColdDrink {
@Override
22
@Override
public String name() {
return "Pepsi";
}
}
Step 5
Create a Meal class having Item objects defined above.
Meal.java
import java.util.ArrayList;
import java.util.List;
System.out.print("Item : "+item.name());
System.out.print(", Packing : "+item.packing().pack());
System.out.println(", Price : "+item.price());
}
}
}
Step 6
Create a MealBuilder class, the actual builder class responsible to create Meal
objects.
MealBuilder.java
public class MealBuilder {
Step 7
BuiderPatternDemo uses MealBuider to demonstrate builder pattern.
BuilderPatternDemo.java
public class BuilderPatternDemo {
24
Step 8
Verify the output.
Veg Meal
Item : Veg Burger, Packing : Wrapper, Price : 25.0
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
25
6. 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 ways 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, an object is to be created after a costly database operation.
We can cache the object, return its clone on next request and update the database
as and when needed thus reducing database calls.
Implementation
We are 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.
PrototypePatternDemo, our demo class, will use ShapeCache class to get
a Shape object.
26
Step 1
Create an abstract class implementing Clonable interface.
Shape.java
public abstract class Shape implements Cloneable {
27
Step 2
Create concrete classes extending the above class.
Rectangle.java
public class Rectangle extends Shape {
public Rectangle(){
type = "Rectangle";
}
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
public class Square extends Shape {
public Square(){
type = "Square";
}
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
public class Circle extends Shape {
public Circle(){
type = "Circle";
28
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
Step 3
Create a class to get concrete classes from database and store them in
a Hashtable.
ShapeCache.java
import java.util.Hashtable;
square.setId("2");
shapeMap.put(square.getId(),square);
Step 4
PrototypePatternDemo uses ShapeCache class to get clones of shapes stored in
aHashtable.
PrototypePatternDemo.java
public class PrototypePatternDemo {
public static void main(String[] args) {
ShapeCache.loadCache();
Step 5
Verify the output.
Shape : Circle
Shape : Square
Shape : Rectangle
30
31
7. 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 plugin
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 have a MediaPlayer interface and a concrete class AudioPlayer implementing
theMediaPlayer interface. AudioPlayer can play mp3 format audio files by default.
We are having another interface AdvancedMediaPlayer and concrete classes
implementing the AdvancedMediaPlayer interface. These classes can play vlc and
mp4 format files.
We want to make AudioPlayer to play other formats as well. To attain this, we
have
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.
32
Step 1
Create interfaces for Media Player and Advanced Media Player.
MediaPlayer.java
public interface MediaPlayer {
public void play(String audioType, String fileName);
}
AdvancedMediaPlayer.java
public interface AdvancedMediaPlayer {
public void playVlc(String fileName);
public void playMp4(String fileName);
}
Step 2
Create concrete classes implementing the AdvancedMediaPlayer interface.
33
VlcPlayer.java
public class VlcPlayer implements AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
System.out.println("Playing vlc file. Name: "+ fileName);
}
@Override
public void playMp4(String fileName) {
//do nothing
}
}
Mp4Player.java
public class Mp4Player implements AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
//do nothing
}
@Override
public void playMp4(String fileName) {
System.out.println("Playing mp4 file. Name: "+ fileName);
}
}
Step 3
Create adapter class implementing the MediaPlayer interface.
MediaAdapter.java
public class MediaAdapter implements MediaPlayer {
34
AdvancedMediaPlayer advancedMusicPlayer;
@Override
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("vlc")){
advancedMusicPlayer.playVlc(fileName);
}else if(audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer.playMp4(fileName);
}
}
}
Step 4
Create concrete class implementing the MediaPlayer interface.
AudioPlayer.java
public class AudioPlayer implements MediaPlayer {
MediaAdapter mediaAdapter;
@Override
public void play(String audioType, String fileName) {
}
//mediaAdapter is providing support to play other file formats
else if(audioType.equalsIgnoreCase("vlc")
|| audioType.equalsIgnoreCase("mp4")){
mediaAdapter = new MediaAdapter(audioType);
mediaAdapter.play(audioType, fileName);
}
else{
System.out.println("Invalid media. "+
audioType + " format not supported");
}
}
}
Step 5
Use the AudioPlayer to play different types of audio formats.
AdapterPatternDemo.java
public class AdapterPatternDemo {
public static void main(String[] args) {
AudioPlayer audioPlayer = new AudioPlayer();
Step 6
Verify the output.
Playing mp3 file. Name: beyond the horizon.mp3
Playing mp4 file. Name: alone.mp4
36
37
8. BRIDGE PATTERN
Bridge is used when 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
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 have a 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.
38
DrawAPI.java
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
Step 2
Create concrete bridge implementer classes implementing the DrawAPI interface.
RedCircle.java
public class RedCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: red, radius: "
+ radius +", x: " +x+", "+ y +"]");
}
}
GreenCircle.java
public class GreenCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: green, radius: "
+ radius +", x: " +x+", "+ y +"]");
}
}
Step 3
Create an abstract class Shape using the DrawAPI interface.
Shape.java
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
39
this.drawAPI = drawAPI;
}
public abstract void draw();
}
Step 4
Create concrete class implementing the Shape interface.
Circle.java
public class Circle extends Shape {
private int x, y, radius;
Step 5
Use the Shape and DrawAPI classes to draw different colored circles.
BridgePatternDemo.java
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());
redCircle.draw();
40
greenCircle.draw();
}
}
Step 6
Verify the output.
Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[
41
9. FILTER PATTERN
Filter pattern or Criteria pattern is a design pattern that enables developers to
filter a set of objects using different criteria and chaining them in a decoupled way
through logical operations. This type of design pattern comes under structural
pattern as this pattern combines multiple criteria to obtain single criteria.
Implementation
We are 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.
Step 1
Create a class on which criteria is to be applied.
42
Person.java
public class Person {
Step 2
Create an interface for Criteria.
Criteria.java
import java.util.List;
43
Step 3
Create concrete classes implementing the Criteria interface.
CriteriaMale.java
import java.util.ArrayList;
import java.util.List;
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> malePersons = new ArrayList<Person>();
for (Person person : persons) {
if(person.getGender().equalsIgnoreCase("MALE")){
malePersons.add(person);
}
}
return malePersons;
}
}
CriteriaFemale.java
import java.util.ArrayList;
import java.util.List;
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> femalePersons = new ArrayList<Person>();
for (Person person : persons) {
if(person.getGender().equalsIgnoreCase("FEMALE")){
femalePersons.add(person);
}
44
}
return femalePersons;
}
}
CriteriaSingle.java
import java.util.ArrayList;
import java.util.List;
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> singlePersons = new ArrayList<Person>();
for (Person person : persons) {
if(person.getMaritalStatus().equalsIgnoreCase("SINGLE")){
singlePersons.add(person);
}
}
return singlePersons;
}
}
AndCriteria.java
import java.util.List;
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> firstCriteriaPersons = criteria.meetCriteria(persons);
return otherCriteria.meetCriteria(firstCriteriaPersons);
}
}
OrCriteria.java
import java.util.List;
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> firstCriteriaItems = criteria.meetCriteria(persons);
List<Person> otherCriteriaItems = otherCriteria.meetCriteria(persons);
Step 4
Use different Criteria and their combination to filter out persons.
CriteriaPatternDemo.java
public class CriteriaPatternDemo {
public static void main(String[] args) {
List<Person> persons = new ArrayList<Person>();
System.out.println("Males: ");
printPersons(male.meetCriteria(persons));
System.out.println("\nFemales: ");
printPersons(female.meetCriteria(persons));
Step 5
Verify the output.
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 ]
48
49
Implementation
We have 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.
50
Step 1
Create Employee class having list of Employee objects.
Employee.java
import java.util.ArrayList;
import java.util.List;
// constructor
public Employee(String name,String dept, int sal) {
this.name = name;
this.dept = dept;
this.salary = sal;
subordinates = new ArrayList<Employee>();
}
Step 2
Use the Employee class to create and print employee hierarchy.
CompositePatternDemo.java
public class CompositePatternDemo {
public static void main(String[] args) {
Employee CEO = new Employee("John","CEO", 30000);
CEO.add(headSales);
CEO.add(headMarketing);
headSales.add(salesExecutive1);
headSales.add(salesExecutive2);
headMarketing.add(clerk1);
headMarketing.add(clerk2);
System.out.println(CEO);
for (Employee headEmployee : CEO.getSubordinates()) {
System.out.println(headEmployee);
for (Employee employee : headEmployee.getSubordinates()) {
System.out.println(employee);
}
}
}
}
Step 3
Verify the output.
Employee :[ Name : John, dept : CEO, salary :30000 ]
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 ]
53
Implementation
We are going to create a Shape interface and concrete classes implementing
the Shape interface. We will then create an abstract decorator
class ShapeDecorator implementing the Shape interface and having Shape object
as its instance variable.
RedShapeDecorator is concrete class implementing ShapeDecorator.
DecoratorPatternDemo, our
decorate Shape objects.
demo
class,
will
use
RedShapeDecorator
to
54
Step 1
Create an interface.
Shape.java
public interface Shape {
void draw();
}
Step 2
Create concrete classes implementing the same interface.
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Rectangle");
}
}
Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Circle");
}
}
Step 3
Create abstract decorator class implementing the Shape interface.
ShapeDecorator.java
public abstract class ShapeDecorator implements Shape {
55
Step 4
Create concrete decorator class extending the ShapeDecorator class.
RedShapeDecorator.java
public class RedShapeDecorator extends ShapeDecorator {
@Override
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
56
Step 5
Use the RedShapeDecorator to decorate Shape objects.
DecoratorPatternDemo.java
public class DecoratorPatternDemo {
public static void main(String[] args) {
Step 6
Verify the output.
Circle with normal border
Shape: Circle
Shape: Rectangle
Border Color: Red
58
Implementation
We are 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 delegate calls to these classes.
FacadePatternDemo, our demo class, will use ShapeMaker class to show the
results.
Step 1
Create an interface.
Shape.java
public interface Shape {
void draw();
59
Step 2
Create concrete classes implementing the same interface.
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle::draw()");
}
}
Square.java
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Square::draw()");
}
}
Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle::draw()");
}
}
60
Step 3
Create a facade class.
ShapeMaker.java
public class ShapeMaker {
private Shape circle;
private Shape rectangle;
private Shape square;
public ShapeMaker() {
circle = new Circle();
rectangle = new Rectangle();
square = new Square();
}
Step 4
Use the facade to draw various types of shapes.
FacadePatternDemo.java
public class FacadePatternDemo {
public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();
61
shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
}
}
Step 5
Verify the output.
Circle::draw()
Rectangle::draw()
Square::draw()
62
Implementation
We are 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 has 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,
it checks the circle object in its HashMap. If object of Circle is 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.
63
Step 1
Create an interface.
Shape.java
public interface Shape {
void draw();
}
Step 2
Create concrete class implementing the same interface.
Circle.java
public class Circle implements Shape {
private String color;
private int x;
private int y;
private int radius;
64
@Override
public void draw() {
System.out.println("Circle: Draw() [Color : " + color
+", x : " + x +", y :" + y +", radius :" + radius);
}
}
Step 3
Create a factory to generate the object of concrete class based on given
information.
ShapeFactory.java
import java.util.HashMap;
65
if(circle == null) {
circle = new Circle(color);
circleMap.put(color, circle);
System.out.println("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.
FlyweightPatternDemo.java
public class FlyweightPatternDemo {
private static final String colors[] =
{ "Red", "Green", "Blue", "White", "Black" };
public static void main(String[] args) {
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
67
68
Implementation
We are going to create an Image interface and concrete classes implementing
the Image interface. ProxyImage is a proxy class to reduce memory footprint
of RealImage object loading.
ProxyPatternDemo, our demo class, will use ProxyImage to get an Image object
to load and display as it needs.
Step 1
Create an interface.
Image.java
public interface Image {
void display();
}
69
Step 2
Create concrete classes implementing the same interface.
RealImage.java
public class RealImage implements Image {
@Override
public void display() {
System.out.println("Displaying " + fileName);
}
ProxyImage.java
public class ProxyImage implements Image{
@Override
70
Step 3
Use the ProxyImage to get object of RealImage class when required.
ProxyPatternDemo.java
public class ProxyPatternDemo {
public static void main(String[] args) {
Image image = new ProxyImage("test_10mb.jpg");
Step 4
Verify the output.
Loading test_10mb.jpg
Displaying test_10mb.jpg
Displaying test_10mb.jpg
71
Implementation
We have created an abstract class AbstractLogger with a level of logging. Then we
have created three types of loggers extending the AbstractLogger. Each logger
checks the level of message to its level and prints accordingly otherwise does not
print and pass the message to its next logger.
72
Step 1
Create an abstract logger class.
AbstractLogger.java
public abstract class AbstractLogger {
public static int INFO = 1;
public static int DEBUG = 2;
public static int ERROR = 3;
73
Step 2
Create concrete classes extending the logger.
ConsoleLogger.java
public class ConsoleLogger extends AbstractLogger {
@Override
protected void write(String message) {
System.out.println("Standard Console::Logger: " + message);
}
}
ErrorLogger.java
public class ErrorLogger extends AbstractLogger {
@Override
protected void write(String message) {
System.out.println("Error Console::Logger: " + message);
}
}
FileLogger.java
public class FileLogger extends AbstractLogger {
@Override
protected void write(String message) {
System.out.println("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.
ChainPatternDemo.java
public class ChainPatternDemo {
errorLogger.setNextLogger(fileLogger);
fileLogger.setNextLogger(consoleLogger);
return errorLogger;
}
loggerChain.logMessage(AbstractLogger.INFO,
"This is an information.");
loggerChain.logMessage(AbstractLogger.DEBUG,
75
loggerChain.logMessage(AbstractLogger.ERROR,
"This is an error information.");
}
}
Step 4
Verify the output.
Standard Console::Logger: This is an information.
File::Logger: This is a debug level information.
Standard Console::Logger: This is a 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.
76
Implementation
We have created an interface Order which is acting as a command. We have
created a Stock class which acts as a request. We have concrete command
classes BuyStock and SellStock implementing Order interface which will do actual
command processing. A class Broker is created which acts as an invoker object.
It can take and place orders.
Broker object uses command pattern to identify which object will execute which
command based on the type of command. CommandPatternDemo, our demo
class, will use Broker class to demonstrate command pattern.
77
Step 1
Create a command interface.
Order.java
public interface Order {
void execute();
}
Step 2
Create a request class.
Stock.java
public class Stock {
Step 3
Create concrete classes implementing the Order interface.
BuyStock.java
public class BuyStock implements Order {
private Stock abcStock;
78
SellStock.java
public class SellStock implements Order {
private Stock abcStock;
Step 4
Create command invoker class.
Broker.java
import java.util.ArrayList;
import java.util.List;
Step 5
Use the Broker class to take and execute commands.
CommandPatternDemo.java
public class CommandPatternDemo {
public static void main(String[] args) {
Stock abcStock = new Stock();
broker.placeOrders();
}
}
Step 6
Verify the output.
Stock [ Name: ABC, Quantity: 10 ] bought
Stock [ Name: ABC, Quantity: 10 ] sold
80
Implementation
We are 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 are OrExpression
and AndExpression which are used to create combinational expressions.
InterpreterPatternDemo, our demo class, will use Expression class to create rules
and demonstrate parsing of expressions.
81
Step 1
Create an expression interface.
Expression.java
public interface Expression {
public boolean interpret(String context);
}
Step 2
Create concrete classes implementing the above interface.
TerminalExpression.java
public class TerminalExpression implements Expression {
@Override
public boolean interpret(String context) {
if(context.contains(data)){
return true;
}
return false;
}
}
OrExpression.java
public class OrExpression implements Expression {
@Override
public boolean interpret(String context) {
return expr1.interpret(context) || expr2.interpret(context);
}
}
AndExpression.java
public class AndExpression implements Expression {
@Override
public boolean interpret(String context) {
return expr1.interpret(context) && expr2.interpret(context);
}
}
Step 3
InterpreterPatternDemo uses Expression class to create rules and then parse
them.
83
InterpreterPatternDemo.java
public class InterpreterPatternDemo {
Step 4
Verify the output.
John is male? true
Julie is a married woman? true
84
Implementation
We are going to create an Iterator interface which includes navigation method and
a Container interface which returns the iterator. Concrete classes implementing
the Container interface will be responsible to implement Iterator interface and use
it.
IteratorPatternDemo, our demo class, will use NamesRepository, a concrete class
implementation, to print Names stored as a collection in NamesRepository.
Step 1
Create interfaces.
Iterator.java
public interface Iterator {
public boolean hasNext();
public Object next();
}
85
Container.java
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.
NameRepository.java
public class NameRepository implements Container {
public String names[] = {"Robert" , "John" ,"Julie" , "Lora"};
@Override
public Iterator getIterator() {
return new NameIterator();
}
int index;
@Override
public boolean hasNext() {
if(index < names.length){
return true;
}
return false;
}
@Override
public Object next() {
if(this.hasNext()){
return names[index++];
86
}
return null;
}
}
}
Step 3
Use the NameRepository to get iterator and print names.
IteratorPatternDemo.java
public class IteratorPatternDemo {
Step 4
Verify the output.
Name : Robert
Name : John
Name : Julie
Name : Lora
87
Implementation
We are 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
have
created
two
classes ChatRoom and User. User objects will use ChatRoom method to share their
messages.
MediatorPatternDemo, our demo
communication between them.
class,
will
use
User
objects
to
show
Step 1
Create mediator class.
ChatRoom.java
import java.util.Date;
Step 2
Create user class.
User.java
public class User {
private String name;
= name;
Step 3
Use the User object to show communications between them.
MediatorPatternDemo.java
public class MediatorPatternDemo {
public static void main(String[] args) {
User robert = new User("Robert");
User john = new User("John");
robert.sendMessage("Hi! John!");
89
john.sendMessage("Hello! Robert!");
}
}
Step 4
Verify the output.
Thu Jan 31 16:05:46 IST 2013 [Robert] : Hi! John!
Thu Jan 31 16:05:46 IST 2013 [John] : Hello! Robert!
90
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 is responsible to restore object state from Memento. We have to
create Memento, Originator, and CareTaker classes.
MementoPatternDemo, our demo class, will use CareTaker and Originator objects
to show restoration of object states.
Step 1
Create Memento class.
Memento.java
public class Memento {
private String state;
91
Step 2
Create Originator class.
Originator.java
public class Originator {
private String state;
Step 3
Create CareTaker class.
CareTaker.java
import java.util.ArrayList;
import java.util.List;
Step 4
Use CareTaker and Originator objects.
MementoPatternDemo.java
public class MementoPatternDemo {
public static void main(String[] args) {
Originator originator = new Originator();
CareTaker careTaker = new CareTaker();
originator.setState("State #1");
originator.setState("State #2");
careTaker.add(originator.saveStateToMemento());
originator.setState("State #3");
careTaker.add(originator.saveStateToMemento());
originator.setState("State #4");
93
}
}
Step 5
Verify the output.
Current State: State #4
First saved State: State #2
Second saved State: State #3
94
Implementation
Observer pattern uses three actor classes. Subject, Observer and Client. Subject
is an object having methods to attach and detach observers to a client object. We
have created an abstract class Observer and a concrete class Subject that is
extending class Observer.
ObserverPatternDemo, our demo class, will use Subject and concrete class object
to show observer pattern in action.
95
Step 1
Create Subject class.
Subject.java
import java.util.ArrayList;
import java.util.List;
96
Step 2
Create Observer class.
Observer.java
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
Step 3
Create concrete observer classes
BinaryObserver.java
public class BinaryObserver extends Observer{
@Override
public void update() {
System.out.println( "Binary String: "
+ Integer.toBinaryString( subject.getState() ) );
}
}
OctalObserver.java
public class OctalObserver extends Observer{
@Override
public void update() {
System.out.println( "Octal String: "
+ Integer.toOctalString( subject.getState() ) );
}
}
HexaObserver.java
public class HexaObserver extends Observer{
@Override
public void update() {
System.out.println( "Hex String: "
+ Integer.toHexString( subject.getState() ).toUpperCase() );
}
}
Step 4
Use Subject and concrete observer objects.
ObserverPatternDemo.java
public class ObserverPatternDemo {
public static void main(String[] args) {
Subject subject = new Subject();
new HexaObserver(subject);
new OctalObserver(subject);
new BinaryObserver(subject);
98
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
99
Implementation
We are going to create a State interface defining an action and concrete state
classes implementing the State interface. Context is a class which carries a State.
StatePatternDemo, our demo class, will use Context and state objects to
demonstrate change in Context behavior based on type of state it is in.
Step 1
Create an interface.
100
State.java
public interface State {
public void doAction(Context context);
}
Step 2
Create concrete classes implementing the same interface.
StartState.java
public class StartState implements State {
StopState.java
public class StopState implements State {
Step 3
Create Context Class.
Context.java
public class Context {
private State state;
public Context(){
state = null;
}
Step 4
Use the Context to see change in behavior when State changes.
StatePatternDemo.java
public class StatePatternDemo {
public static void main(String[] args) {
Context context = new Context();
System.out.println(context.getState().toString());
stopState.doAction(context);
System.out.println(context.getState().toString());
}
}
Step 5
Verify the output.
Player is in start state
Start State
Player is in stop state
Stop State
103
Implementation
We are going to create an AbstractCustomer abstract class defining operations.
Here concrete classes will extend 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 the
use of Null Object pattern.
104
Step 1
Create an abstract class.
AbstractCustomer.java
public abstract class AbstractCustomer {
protected String name;
public abstract boolean isNil();
public abstract String getName();
}
Step 2
Create concrete classes extending the above class.
RealCustomer.java
public class RealCustomer extends AbstractCustomer {
@Override
public String getName() {
return name;
}
@Override
public boolean isNil() {
return false;
}
}
NullCustomer.java
public class NullCustomer extends AbstractCustomer {
105
@Override
public String getName() {
return "Not Available in Customer Database";
}
@Override
public boolean isNil() {
return true;
}
}
Step 3
Create CustomerFactory Class.
CustomerFactory.java
public class CustomerFactory {
Step 4
Use the CustomerFactory to get either RealCustomer or NullCustomer objects
based on the name of customer passed to it.
NullPatternDemo.java
106
System.out.println("Customers");
System.out.println(customer1.getName());
System.out.println(customer2.getName());
System.out.println(customer3.getName());
System.out.println(customer4.getName());
}
}
Step 5
Verify the output.
Customers
Rob
Not Available in Customer Database
Julie
Not Available in Customer Database
107
Implementation
We are going to create a Strategy interface defining an 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.
Step 1
Create an interface.
Strategy.java
public interface Strategy {
public int doOperation(int num1, int num2);
108
Step 2
Create concrete classes implementing the same interface.
OperationAdd.java
public class OperationAdd implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
OperationSubstract.java
public class OperationSubstract implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
OperationMultiply.java
public class OperationMultiply implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
Step 3
Create Context Class.
109
Context.java
public class Context {
private Strategy strategy;
Step 4
Use the Context to see change in behavior when it changes its Strategy.
StrategyPatternDemo.java
public class StrategyPatternDemo {
public static void main(String[] args) {
Context context = new Context(new OperationAdd());
System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
Step 5
Verify the output.
110
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
111
Implementation
We are 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 that extend Game and override its methods.
TemplatePatternDemo, our demo class, will use Game to demonstrate use of
template pattern.
Step 1
Create an abstract class with a template method being final.
112
Game.java
public abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
//template method
public final void play(){
//start game
startPlay();
//end game
endPlay();
}
}
Step 2
Create concrete classes extending the above class.
Cricket.java
public class Cricket extends Game {
@Override
void endPlay() {
System.out.println("Cricket Game Finished!");
}
@Override
void initialize() {
System.out.println("Cricket Game Initialized! Start playing.");
113
@Override
void startPlay() {
System.out.println("Cricket Game Started. Enjoy the game!");
}
}
Football.java
public class Football extends Game {
@Override
void endPlay() {
System.out.println("Football Game Finished!");
}
@Override
void initialize() {
System.out.println("Football Game Initialized! Start playing.");
}
@Override
void startPlay() {
System.out.println("Football Game Started. Enjoy the game!");
}
}
Step 3
Use the Game's template method play() to demonstrate a defined way of playing
game.
TemplatePatternDemo.java
114
Step 4
Verify the output.
Cricket Game Initialized! Start playing.
Cricket Game Started. Enjoy the game!
Cricket Game Finished!
115
Implementation
We are going to create a ComputerPart interface defining accept operation.
Keyboard, Mouse, Monitor, and Computer are concrete classes implementing
ComputerPart interface. We will 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 and ComputerPartVisitor
classes to demonstrate use of visitor pattern.
116
Step 1
Define an interface to represent element.
ComputerPart.java
public interface ComputerPart {
public void accept(ComputerPartVisitor computerPartVisitor);
}
Step 2
Create concrete classes extending the above class.
Keyboard.java
public class Keyboard implements ComputerPart {
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
computerPartVisitor.visit(this);
}
}
Monitor.java
public class Monitor implements ComputerPart {
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
computerPartVisitor.visit(this);
}
}
Mouse.java
public class Mouse implements ComputerPart {
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
117
computerPartVisitor.visit(this);
}
}
Computer.java
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 < parts.length; i++) {
parts[i].accept(computerPartVisitor);
}
computerPartVisitor.visit(this);
}
}
Step 3
Define an interface to represent visitor.
ComputerPartVisitor.java
public interface ComputerPartVisitor {
public void visit(Computer computer);
public void visit(Mouse mouse);
public void visit(Keyboard keyboard);
public void visit(Monitor monitor);
}
118
Step 4
Create concrete visitor implementing the above class.
ComputerPartDisplayVisitor.java
public class ComputerPartDisplayVisitor implements ComputerPartVisitor {
@Override
public void visit(Computer computer) {
System.out.println("Displaying Computer.");
}
@Override
public void visit(Mouse mouse) {
System.out.println("Displaying Mouse.");
}
@Override
public void visit(Keyboard keyboard) {
System.out.println("Displaying Keyboard.");
}
@Override
public void visit(Monitor monitor) {
System.out.println("Displaying Monitor.");
}
}
Step 5
Use the ComputerPartDisplayVisitor to display parts of Computer.
VisitorPatternDemo.java
public class VisitorPatternDemo {
public static void main(String[] args) {
119
Step 6
Verify the output.
Displaying Mouse.
Displaying Keyboard.
Displaying Monitor.
Displaying Computer.
120
Model - Model represents an object or JAVA POJO carrying data. It can also
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 are going to create a Student object acting as a model. StudentView 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.
121
Step 1
Create Model.
Student.java
public class Student {
private String rollNo;
private String name;
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Step 2
Create View.
StudentView.java
public class StudentView {
public void printStudentDetails(String studentName, String studentRollNo){
System.out.println("Student: ");
System.out.println("Name: " + studentName);
System.out.println("Roll No: " + studentRollNo);
}
}
122
Step 3
Create Controller.
StudentController.java
public class StudentController {
private Student model;
private StudentView view;
123
Step 4
Use the StudentController methods to demonstrate MVC design pattern usage.
MVCPatternDemo.java
public class MVCPatternDemo {
public static void main(String[] args) {
controller.updateView();
controller.updateView();
}
124
Step 5
Verify the output.
Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10
125
Business Delegate - A single entry point class for client entities to provide
access to Business Service methods.
Implementation
We are going to create a Client, BusinessDelegate, BusinessService,
LookUpService, JMSService and EJBService representing various entities of
Business Delegate patterns.
BusinessDelegatePatternDemo, our demo class, will use BusinessDelegate and
Client to demonstrate use of Business Delegate pattern.
126
Step 1
Create BusinessService Interface.
BusinessService.java
public interface BusinessService {
public void doProcessing();
}
Step 2
Create concrete Service classes.
EJBService.java
public class EJBService implements BusinessService {
@Override
public void doProcessing() {
System.out.println("Processing task by invoking EJB Service");
127
}
}
JMSService.java
public class JMSService implements BusinessService {
@Override
public void doProcessing() {
System.out.println("Processing task by invoking JMS Service");
}
}
Step 3
Create Business Lookup Service.
BusinessLookUp.java
public class BusinessLookUp {
public BusinessService getBusinessService(String serviceType){
if(serviceType.equalsIgnoreCase("EJB")){
return new EJBService();
}else {
return new JMSService();
}
}
}
Step 4
Create Business Delegate.
BusinessDelegate.java
public class BusinessDelegate {
private BusinessLookUp lookupService = new BusinessLookUp();
private BusinessService businessService;
private String serviceType;
128
Step 5
Create Client.
Client.java
public class Client {
BusinessDelegate businessService;
= businessService;
Step 6
Use BusinessDelegate and Client classes to demonstrate Business Delegate
pattern.
BusinessDelegatePatternDemo.java
public class BusinessDelegatePatternDemo {
129
businessDelegate.setServiceType("JMS");
client.doTask();
}
}
Step 7
Verify the output.
Processing task by invoking EJB Service
Processing task by invoking JMS Service
130
Implementation
We are 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.
131
Step 1
Create Dependent Objects.
DependentObject1.java
public class DependentObject1 {
DependentObject2.java
public class DependentObject2 {
132
Step 2
Create Coarse Grained Object.
CoarseGrainedObject.java
public class CoarseGrainedObject {
DependentObject1 do1 = new DependentObject1();
DependentObject2 do2 = new DependentObject2();
Step 3
Create Composite Entity.
CompositeEntity.java
public class CompositeEntity {
private CoarseGrainedObject cgo = new CoarseGrainedObject();
133
Step 4
Create Client class to use Composite Entity.
Client.java
public class Client {
private CompositeEntity compositeEntity = new CompositeEntity();
Step 5
Use the Client to demonstrate Composite Entity design pattern usage.
CompositeEntityPatternDemo.java
public class CompositeEntityPatternDemo {
public static void main(String[] args) {
Client client = new Client();
client.setData("Test", "Data");
client.printData();
client.setData("Second Test", "Data1");
client.printData();
}
}
134
Step 6
Verify the output.
Data: Test
Data: Data
Data: Second Test
Data: Data1
135
Implementation
We are going to create a Student object acting as a Model or Value
Object.StudentDao is Data Access Object Interface. StudentDaoImpl is concrete
class implementing Data Access Object Interface. DaoPatternDemo, our demo
class, will use StudentDao to demonstrate the use of Data Access Object pattern.
136
Step 1
Create Value Object.
Student.java
public class Student {
private String name;
private int rollNo;
Step 2
Create Data Access Object Interface.
137
StudentDao.java
import java.util.List;
Step 3
Create concrete class implementing above interface.
StudentDaoImpl.java
import java.util.ArrayList;
import java.util.List;
public StudentDaoImpl(){
students = new ArrayList<Student>();
Student student1 = new Student("Robert",0);
Student student2 = new Student("John",1);
students.add(student1);
students.add(student2);
}
@Override
public void deleteStudent(Student student) {
students.remove(student.getRollNo());
System.out.println("Student: Roll No " + student.getRollNo()
+", deleted from database");
138
@Override
public Student getStudent(int rollNo) {
return students.get(rollNo);
}
@Override
public void updateStudent(Student student) {
students.get(student.getRollNo()).setName(student.getName());
System.out.println("Student: Roll No " + student.getRollNo()
+", updated in the database");
}
}
Step 4
Use the StudentDao to demonstrate Data Access Object pattern usage.
DaoPatternDemo.java
public class DaoPatternDemo {
public static void main(String[] args) {
StudentDao studentDao = new StudentDaoImpl();
//update student
Student student = studentDao.getAllStudents().get(0);
student.setName("Michael");
studentDao.updateStudent(student);
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 ]
140
Front Controller - Single handler for all kinds of requests coming to the
application (either web based/ desktop based).
View - Views are the object for which the requests are made.
Implementation
We are going to create a FrontController and Dispatcher to act as Front Controller
and Dispatcher correspondingly. HomeView and StudentView represent various
views for which requests can come to front controller.
FrontControllerPatternDemo, our demo class,
demonstrate Front Controller Design Pattern.
will
use
FrontController
to
141
Step 1
Create Views.
HomeView.java
public class HomeView {
public void show(){
System.out.println("Displaying Home Page");
}
}
StudentView.java
public class StudentView {
public void show(){
System.out.println("Displaying Student Page");
}
}
Step 2
Create Dispatcher.
Dispatcher.java
public class Dispatcher {
private StudentView studentView;
private HomeView homeView;
public Dispatcher(){
studentView = new StudentView();
homeView = new HomeView();
}
}
}
}
Step 3
Create FrontController
FrontController.java
public class FrontController {
public FrontController(){
dispatcher = new Dispatcher();
}
Step 4
Use the FrontController to demonstrate Front Controller Design Pattern.
FrontControllerPatternDemo.java
public class FrontControllerPatternDemo {
public static void main(String[] args) {
FrontController frontController = new FrontController();
frontController.dispatchRequest("HOME");
frontController.dispatchRequest("STUDENT");
}
}
Step 5
Verify the output.
Page requested: HOME
User is authenticated successfully.
Displaying Home Page
Page requested: STUDENT
User is authenticated successfully.
Displaying Student Page
144
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.
Filter Manager - Filter Manager manages the filters and Filter Chain.
Client - Client is the object who sends request to the Target object.
Implementation
We are going to create a FilterChain, FilterManager, Target, and Client as various
objects representing our entities. AuthenticationFilter and DebugFilter represent
concrete filters.
InterceptingFilterDemo, our demo
Intercepting Filter Design Pattern.
class,
will
use
Client
to
demonstrate
145
Step 1
Create Filter interface.
Filter.java
public interface Filter {
public void execute(String request);
}
Step 2
Create concrete filters.
AuthenticationFilter.java
public class AuthenticationFilter implements Filter {
public void execute(String request){
System.out.println("Authenticating request: " + request);
}
146
DebugFilter.java
public class DebugFilter implements Filter {
public void execute(String request){
System.out.println("request log: " + request);
}
}
Step 3
Create Target
Target.java
public class Target {
public void execute(String request){
System.out.println("Executing request: " + request);
}
}
Step 4
Create Filter Chain.
FilterChain.java
import java.util.ArrayList;
import java.util.List;
147
Step 5
Create Filter Manager.
FilterManager.java
public class FilterManager {
FilterChain filterChain;
148
Step 6
Create Client.
Client.java
public class Client {
FilterManager filterManager;
Step 7
Use the Client to demonstrate Intercepting Filter Design Pattern.
InterceptingFilterDemo.java
public class InterceptingFilterDemo {
public static void main(String[] args) {
FilterManager filterManager = new FilterManager(new Target());
filterManager.setFilter(new AuthenticationFilter());
filterManager.setFilter(new DebugFilter());
149
Step 8
Verify the output.
Authenticating request: HOME
request log: HOME
Executing request: HOME
150
Service - Actual Service which will process the request. Reference of such
service is to be looked upon in JNDI server.
Client - Client is the object that invokes the services via ServiceLocator.
Implementation
We are going to create a ServiceLocator, InitialContext, Cache, and Service as
various objects representing our entities.Service1 and Service2 represent
concrete services.
ServiceLocatorPatternDemo, our demo class, is acting as a client here and will use
ServiceLocator to demonstrate Service Locator Design Pattern.
151
Step 1
Create Service interface.
Service.java
public interface Service {
public String getName();
public void execute();
}
Step 2
Create concrete services.
Service1.java
public class Service1 implements Service {
public void execute(){
152
System.out.println("Executing Service1");
}
@Override
public String getName() {
return "Service1";
}
}
Service2.java
public class Service2 implements Service {
public void execute(){
System.out.println("Executing Service2");
}
@Override
public String getName() {
return "Service2";
}
}
Step 3
Create InitialContext for JNDI lookup
InitialContext.java
public class InitialContext {
public Object lookup(String jndiName){
if(jndiName.equalsIgnoreCase("SERVICE1")){
System.out.println("Looking up and creating a new Service1 object");
return null;
}
}
Step 4
Create Cache.
Cache.java
import java.util.ArrayList;
import java.util.List;
public Cache(){
services = new ArrayList<Service>();
}
"+serviceName+" object");
return service;
}
}
return null;
}
}
}
if(!exists){
services.add(newService);
}
}
}
Step 5
Create Service Locator.
ServiceLocator.java
public class ServiceLocator {
private static Cache cache;
static {
cache = new Cache();
}
if(service != null){
return service;
}
155
Step 6
Use the ServiceLocator to demonstrate Service Locator Design Pattern.
ServiceLocatorPatternDemo.java
public class ServiceLocatorPatternDemo {
public static void main(String[] args) {
Service service = ServiceLocator.getService("Service1");
service.execute();
service = ServiceLocator.getService("Service2");
service.execute();
service = ServiceLocator.getService("Service1");
service.execute();
service = ServiceLocator.getService("Service2");
service.execute();
}
}
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
156
Business Object - Business Service fills the Transfer Object with data.
Implementation
We are going to create a StudentBO as Business Object, Student as Transfer
Object 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.
157
Step 1
Create Transfer Object.
StudentVO.java
public class StudentVO {
private String name;
private int rollNo;
158
Step 2
Create Business Object.
StudentBO.java
import java.util.ArrayList;
import java.util.List;
public StudentBO(){
students = new ArrayList<StudentVO>();
StudentVO student1 = new StudentVO("Robert",0);
StudentVO student2 = new StudentVO("John",1);
students.add(student1);
students.add(student2);
}
public void deleteStudent(StudentVO student) {
students.remove(student.getRollNo());
System.out.println("Student: Roll No "
+ student.getRollNo() +", deleted from database");
}
159
Step 3
Use the StudentBO to demonstrate Transfer Object Design Pattern.
TransferObjectPatternDemo.java
public class TransferObjectPatternDemo {
public static void main(String[] args) {
StudentBO studentBusinessObject = new StudentBO();
//update student
StudentVO student = studentBusinessObject.getAllStudents().get(0);
student.setName("Michael");
studentBusinessObject.updateStudent(student);
160
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 ]
161