java design pattern tutorial for java expert

Upload: manish-kumar

Post on 10-Feb-2018

231 views

Category:

Documents


1 download

TRANSCRIPT

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    1/169

    Design Patterns in Java Tutorial

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    2/169i

    DESIGN PATTERNS IN JAVA TUTORIAL

    Simply Easy Learning by tutorialspoint.com

    tutorialspoint.com

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    3/169

    ii

    ABOUT THE TUTORIAL

    Design Patterns in Java TutorialDesign patterns represent the best practices used by experienced object-oriented software developers. Design patterns aresolutions to general problems that software developers faced during software development. These solutions were obtainedby trial and error by numerous software developers over quite a substantial period of time.

    This tutorial will take you through step by step approach and examples using Java while learning Design Pattern concepts.

    AudienceThis reference has been prepared for the experienced developers to provide best solutions to certain problems faced

    during software development and for un-experienced developers to learn software design in an easy and faster way.

    PrerequisitesBefore proceeding with this tutorial you should have a good understanding of Java programming language. A basicunderstanding of Eclipse IDE is also required because all the examples have been compiled using Eclipse IDE.

    Copyright & Disclaimer Notice All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com orthis tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission oftutorialspoint.com. Failure to do so is a violation of copyright laws.

    This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the siteor its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains someerrors, please contact us [email protected]

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/22/2019 Java Design Pattern Tutorial for java expert

    4/169

    iii

    Table of Contents

    Design Patterns in Java Tutorial................................................ iAudience ................................................................................... iPrerequisites ............................................................................. iCopyright & Disclaimer Notice................................................... iDesign Pattern Overview.................................................................... 1Common platform for developers............................................................................................ 1Best Practices........................................................................................................................ 2Factory Pattern............................................................................... 3Implementation ............................................................................................ 3Class Diagram ............................................................................................. 3Steps ........................................................................................................... 4

    Abstract Factory Pattern .................................................................... 7Implementation ............................................................................................ 7Class Diagram ............................................................................................. 8Steps ........................................................................................................... 9Singleton Design Pattern .................................................................. 14Implementation .......................................................................................... 14Class Diagram ........................................................................................... 15Steps ......................................................................................................... 16Builder Design Pattern .................................................................... 18Implementation .......................................................................................... 18Class Diagram ........................................................................................... 19Steps ......................................................................................................... 20Prototype Design Pattern.................................................................. 25Implementation .......................................................................................... 25Class Diagram. .......................................................................................... 26Steps ......................................................................................................... 27

    Adapter Design Pattern.................................................................... 30Implementation .......................................................................................... 30Class Diagram ........................................................................................... 31Steps ......................................................................................................... 32Bridge Design Pattern ..................................................................... 35

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    5/169

    iii

    Implementation .......................................................................................... 35Class Diagram ........................................................................................... 36Steps ......................................................................................................... 37Filter Design Pattern

    ...................................................................... 39Implementation .......................................................................................... 39Class Diagram ........................................................................................... 40Steps ......................................................................................................... 41Composite Design Pattern ................................................................. 46Implementation .......................................................................................... 46Class Diagram ........................................................................................... 47Steps ......................................................................................................... 48Decorator Design Pattern ................................................................. 50Implementation .......................................................................................... 50Class Diagram ........................................................................................... 51Steps ......................................................................................................... 52Faade Design Pattern..................................................................... 55Implementation .......................................................................................... 55Class Diagram ........................................................................................... 56Steps ......................................................................................................... 57Flyweight Design Pattern.................................................................. 59Implementation .......................................................................................... 59Class Diagram ........................................................................................... 60Steps ......................................................................................................... 61Proxy Design Pattern ...................................................................... 64Implementation .......................................................................................... 64Class Diagram ........................................................................................... 65Steps ......................................................................................................... 66Chain of Responsibility Design Pattern .................................................. 68Implementation .......................................................................................... 68Class Diagram ........................................................................................... 69Steps ......................................................................................................... 70Command Design Pattern ................................................................. 73Implementation .......................................................................................... 73Class Diagram ........................................................................................... 74Steps ......................................................................................................... 75Interpreter Design Pattern ................................................................ 78Implementation .......................................................................................... 78Class Diagram ........................................................................................... 79

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    6/169

    iii

    Steps ......................................................................................................... 80Iterator Design Pattern .................................................................... 83Implementation .......................................................................................... 83Class Diagram

    ........................................................................................... 84Steps ......................................................................................................... 85Mediator Design Pattern .................................................................. 87Implementation .......................................................................................... 87Class Diagram ........................................................................................... 88Steps ......................................................................................................... 89Memento Design Pattern .................................................................. 91Implementation .......................................................................................... 91Class Diagram ........................................................................................... 92Steps ......................................................................................................... 93Observer Design Pattern................................................................... 95Implementation .......................................................................................... 95Class Diagram ........................................................................................... 96Steps ......................................................................................................... 97State Design Pattern ..................................................................... 100Implementation ........................................................................................ 100Class Diagram ......................................................................................... 101Steps ....................................................................................................... 102Null Object Design Pattern.............................................................. 104Implementation ........................................................................................ 104Class Diagram ......................................................................................... 105Steps ....................................................................................................... 106Strategy Design Pattern ................................................................. 109Implementation ........................................................................................ 109Class Diagram ......................................................................................... 110Steps ....................................................................................................... 111Template Design Pattern ................................................................ 113Implementation ........................................................................................ 113Class Diagram ......................................................................................... 114Steps ....................................................................................................... 115

    Visitor Design Pattern ................................................................... 117Implementation ........................................................................................ 117Class Diagram ......................................................................................... 118Steps ....................................................................................................... 119MVC Design Pattern ..................................................................... 122

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    7/169

    iii

    Implementation ........................................................................................ 122Class Diagram ......................................................................................... 123Steps ....................................................................................................... 124Business Delegate Design Pattern

    ...................................................... 127Implementation ........................................................................................ 127Class Diagram ......................................................................................... 128Steps ....................................................................................................... 129Composite Entity Design Pattern ....................................................... 132Implementation ........................................................................................ 132Class Diagram ......................................................................................... 133Steps ....................................................................................................... 134Data Access Object Design Pattern ..................................................... 137Implementation ........................................................................................ 137Class Diagram ......................................................................................... 138Steps ....................................................................................................... 139Front Controller Design Pattern ........................................................ 142Implementation ........................................................................................ 142Class Diagram ......................................................................................... 143Steps ....................................................................................................... 144Intercepting Filter Design Pattern...................................................... 146Implementation ........................................................................................ 146Class Diagram ......................................................................................... 147Steps ....................................................................................................... 148Service Locator Design Pattern ......................................................... 151Implementation ........................................................................................ 151Class Diagram ......................................................................................... 152Steps ....................................................................................................... 153Transfer Object Design Pattern ......................................................... 157Implementation ........................................................................................ 157Class Diagram ......................................................................................... 158Steps ....................................................................................................... 159

    About tutorialspoint.com ................................................................ 162

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    8/169

    TUTORIALS POINT

    Simply Easy Learning Page 1

    Design Pattern OverviewThis chapter gives a basic idea about Design Patterns starting with their origin, theirevaluation over time and their classifications.

    Design patterns represent the best practices used by experienced object-orientedsoftware developers. Design patterns are solutions to general problems that software developersfaced during software development. These solutions were obtained by trial and error bynumerous software developers over quite a substantial period of time.

    Gang of Four (GOF)

    In 1994, four authors Erich Gamma, Richard Helm; Ralph Johnson und John Vlissides publisheda book titled Design Patterns - Elements of Reusable Object-Oriented 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 designpatterns 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. Forexample, a singleton design pattern signifies use of single object so all developers familiar withsingle design pattern will make use of single object and they can tell each other that program isfollowing a singleton pattern.

    CHAPTER

    1

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    9/169

    TUTORIALS POINT

    Simply Easy Learning Page 2

    Best Practices

    Design patterns have been evolved over a long period of time and they provide best solutions tocertain problems faced during software development. Learning these patterns helps un-experienced 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 Object-Oriented Software, there are 23 design patterns. These patterns can be classified in threecategories: Creational, Structural and behavioral patterns. We'll also discuss another category ofdesign patterns: J2EE design patterns.

    S.N. Pattern & Description

    1

    Creational Patterns

    These design patterns provides way to create objects while hiding the creation logic,rather than instantiating objects directly using new operator. This gives program moreflexibility in deciding which objects need to be created for a given use case.

    2

    Structural PatternsThese design patterns concern class and object composition. Concept of inheritance isused to compose interfaces and define ways to compose objects to obtain newfunctionalities.

    3Behavioral PatternsThese design patterns are specifically concerned with communication between objects.

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

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    10/169

    TUTORIALS POINT

    Simply Easy Learning Page 3

    Factory PatternThis section describes factory pattern and its implementation.

    Factory pattern is one of most used design pattern in Java. This type of design pattern comesunder 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 client and refer tonewly created object using a common interface.

    ImplementationWe're going to create a Shape interface and concrete classes implementing the Shape interface.

    A factory class ShapeFactoryis defined as a next step.

    FactoryPatternDemo, our demo class will use ShapeFactoryto get a Shape object. It will passinformation (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get the type of object itneeds.

    Class Diagram

    CHAPTER

    2

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    11/169

    TUTORIALS POINT

    Simply Easy Learning Page 4

    StepsUse the following steps to implement the above mentioned design pattern.

    Step 1Create an interface.

    Shape.java

    publicinterfaceShape{void draw();

    }

    Step 2Create concrete classes implementing the same interface.

    Rectangle.java

    publicclassRectangleimplementsShape{

    @Overridepublicvoid draw(){

    System.out.println("Inside Rectangle::draw() method.");}

    }

    Square.java

    publicclassSquareimplementsShape{

    @Overridepublicvoid draw(){

    System.out.println("Inside Square::draw() method.");}

    }

    Circle.java

    publicclassCircleimplementsShape{

    @Overridepublicvoid draw(){

    System.out.println("Inside Circle::draw() method.");}

    }

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    12/169

    TUTORIALS POINT

    Simply Easy Learning Page 5

    Step 3

    Create a Factory to generate object of concrete class based on given information.

    ShapeFactory.java

    publicclassShapeFactory{

    //use getShape method to get object of type shapepublicShape getShape(String shapeType){

    if(shapeType ==null){returnnull;

    }if(shapeType.equalsIgnoreCase("CIRCLE")){

    returnnewCircle();}elseif(shapeType.equalsIgnoreCase("RECTANGLE")){

    returnnewRectangle();

    }elseif(shapeType.equalsIgnoreCase("SQUARE")){returnnewSquare();

    }returnnull;

    }}

    Step 4Use the Factory to get object of concrete class by passing an information such as type.

    FactoryPatternDemo.java

    publicclassFactoryPatternDemo{

    publicstaticvoid main(String[] args){ShapeFactory shapeFactory =newShapeFactory();

    //get an object of Circle and call its draw method.Shape shape1 = shapeFactory.getShape("CIRCLE");

    //call draw method of Circleshape1.draw();

    //get an object of Rectangle and call its draw method.Shape shape2 = shapeFactory.getShape("RECTANGLE");

    //call draw method of Rectangleshape2.draw();

    //get an object of Square and call its draw method.Shape shape3 = shapeFactory.getShape("SQUARE");

    //call draw method of circleshape3.draw();

    }}

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    13/169

    TUTORIALS POINT

    Simply Easy Learning Page 6

    Step 5

    Verify the output.

    Inside Circle::draw() method.

    Inside Rectangle::draw() method.

    Inside Square::draw() method.

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    14/169

    TUTORIALS POINT

    Simply Easy Learning Page 7

    Abstract Factory PatternThis section describes abstract factory pattern and its implementation.

    Abstract Factory patterns works around a super-factory which creates other factories. This

    factory is also called as Factory of factories. This type of design pattern comes under creationalpattern 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 theFactory pattern.

    Implementation

    We're going to create a Shape and Colorinterfaces and concrete classes implementing theseinterfaces. We creates an abstract factory classAbstractFactoryas next step. Factory

    classesShapeFactoryand ColorFactoryare defined where each factory extendsAbstractFactory.A factory creator/generator class FactoryProduceris created.

    AbstractFactoryPatternDemo, our demo class uses FactoryProducerto getaAbstractFactoryobject. It will pass information (CIRCLE / RECTANGLE / SQUAREforShape)toAbstractFactoryto get the type of object it needs. It also passes information ( RED / GREEN /BLUEforColor) toAbstractFactoryto get the type of object it needs.

    CHAPTER

    3

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    15/169

    TUTORIALS POINT

    Simply Easy Learning Page 8

    Class Diagram

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    16/169

    TUTORIALS POINT

    Simply Easy Learning Page 9

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1Create an interface for Shapes.

    Shape.java

    publicinterfaceShape{void draw();

    }

    Step 2Create concrete classes implementing the same interface.

    Rectangle.java

    publicclassRectangleimplementsShape{

    @Overridepublicvoid draw(){

    System.out.println("Inside Rectangle::draw() method.");}

    }

    Square.javapublicclassSquareimplementsShape{

    @Overridepublicvoid draw(){

    System.out.println("Inside Square::draw() method.");}

    }

    Circle.java

    publicclassCircleimplementsShape{

    @Overridepublicvoid draw(){

    System.out.println("Inside Circle::draw() method.");}

    }

    Step 3Create an interface for Colors.

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    17/169

    TUTORIALS POINT

    Simply Easy Learning Page 10

    Color.java

    publicinterfaceColor{void fill();

    }

    Step4Create concrete classes implementing the same interface.

    Red.java

    publicclassRedimplementsColor{

    @Overridepublicvoid fill(){

    System.out.println("Inside Red::fill() method.");}

    }

    Green.java

    publicclassGreenimplementsColor{

    @Overridepublicvoid fill(){

    System.out.println("Inside Green::fill() method.");}

    }

    Blue.java

    publicclassBlueimplementsColor{

    @Overridepublicvoid fill(){

    System.out.println("Inside Blue::fill() method.");}

    }

    Step 5Create an Abstract class to get factories for Color and Shape Objects.

    AbstractFactory.java

    publicabstractclassAbstractFactory{abstractColor getColor(String color);abstractShape getShape(String shape);

    }

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    18/169

    TUTORIALS POINT

    Simply Easy Learning Page 11

    Step 6

    Create Factory classes extending AbstractFactory to generate object of concrete class based ongiven information.

    ShapeFactory.java

    publicclassShapeFactoryextendsAbstractFactory{

    @OverridepublicShape getShape(String shapeType){

    if(shapeType ==null){returnnull;

    }if(shapeType.equalsIgnoreCase("CIRCLE")){

    returnnewCircle();}elseif(shapeType.equalsIgnoreCase("RECTANGLE")){

    returnnewRectangle();}elseif(shapeType.equalsIgnoreCase("SQUARE")){returnnewSquare();

    }returnnull;

    }

    @OverrideColor getColor(String color){

    returnnull;}

    }

    ColorFactory.java

    publicclassColorFactoryextendsAbstractFactory{

    @OverridepublicShape getShape(String shapeType){

    returnnull;}

    @OverrideColor getColor(String color){

    if(color ==null){returnnull;

    }if(color.equalsIgnoreCase("RED")){

    returnnewRed();}elseif(color.equalsIgnoreCase("GREEN")){

    returnnewGreen();}elseif(color.equalsIgnoreCase("BLUE")){returnnewBlue();

    }returnnull;

    }}

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    19/169

    TUTORIALS POINT

    Simply Easy Learning Page 12

    Step 7

    Create a Factory generator/producer class to get factories by passing an information such asShape or Color

    FactoryProducer.java

    publicclassFactoryProducer{publicstaticAbstractFactory getFactory(String choice){

    if(choice.equalsIgnoreCase("SHAPE")){returnnewShapeFactory();

    }elseif(choice.equalsIgnoreCase("COLOR")){returnnewColorFactory();

    }returnnull;

    }}

    Step 8Use the FactoryProducer to get AbstractFactory in order to get factories of concrete classes bypassing information such as type.

    AbstractFactoryPatternDemo.java

    publicclassAbstractFactoryPatternDemo{publicstaticvoid main(String[] args){

    //get shape factory

    AbstractFactory shapeFactory =FactoryProducer.getFactory("SHAPE");

    //get an object of Shape CircleShape shape1 = shapeFactory.getShape("CIRCLE");

    //call draw method of Shape Circleshape1.draw();

    //get an object of Shape RectangleShape shape2 = shapeFactory.getShape("RECTANGLE");

    //call draw method of Shape Rectangleshape2.draw();

    //get an object of Shape SquareShape shape3 = shapeFactory.getShape("SQUARE");

    //call draw method of Shape Squareshape3.draw();

    //get color factoryAbstractFactory colorFactory =

    FactoryProducer.getFactory("COLOR");

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    20/169

    TUTORIALS POINT

    Simply Easy Learning Page 13

    //get an object of Color RedColor color1 = colorFactory.getColor("RED");

    //call fill method of Redcolor1.fill();

    //get an object of Color GreenColor color2 = colorFactory.getColor("Green");

    //call fill method of Greencolor2.fill();

    //get an object of Color BlueColor color3 = colorFactory.getColor("BLUE");

    //call fill method of Color Bluecolor3.fill();

    }}

    Step 9Verify 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.

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    21/169

    TUTORIALS POINT

    Simply Easy Learning Page 14

    Singleton Design PatternThis section describes singleton pattern and its implementation.

    Singleton pattern is one of the simplest design patterns in Java. This type of design patterncomes 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 surethat only single object get created. This class provides a way to access its only object which canbe accessed directly without need to instantiate the object of the class.

    Implementation

    We're going to create a SingleObjectclass. SingleObjectclass have its constructor as privateand have a static instance of itself.

    SingleObjectclass provides a static method to get its static instance to outsideworld.SingletonPatternDemo, our demo class will use SingleObjectclass to geta SingleObjectobject.

    CHAPTER

    4

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    22/169

    TUTORIALS POINT

    Simply Easy Learning Page 15

    Class Diagram

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    23/169

    TUTORIALS POINT

    Simply Easy Learning Page 16

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1Create a Singleton Class.

    SingleObject.java

    publicclassSingleObject{

    //create an object of SingleObjectprivatestaticSingleObject instance =newSingleObject();

    //make the constructor private so that this class cannot be//instantiated

    privateSingleObject(){}

    //Get the only object availablepublicstaticSingleObject getInstance(){

    return instance;}

    publicvoid showMessage(){System.out.println("Hello World!");

    }}

    Step 2Get the only object from the singleton class.

    SingletonPatternDemo.java

    publicclassSingletonPatternDemo{publicstaticvoid main(String[] args){

    //illegal construct//Compile Time Error: The constructor SingleObject() is not

    visible//SingleObject object = new SingleObject();

    //Get the only object available

    SingleObjectobject=SingleObject.getInstance();

    //show the messageobject.showMessage();

    }}

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    24/169

    TUTORIALS POINT

    Simply Easy Learning Page 17

    Step 3

    Verify the output.

    Hello World!

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    25/169

    TUTORIALS POINT

    Simply Easy Learning Page 18

    Builder Design PatternThis section describes builder pattern and its implementation.

    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 providesone 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.

    ImplementationWe've considered a business case of fast-food restaurant where a typical meal could be aburger and a cold drink. Burger could be either a Veg Burger or Chicken Burger and will bepacked 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 drinksand concrete classes implementing the Item interface and a Packinginterface representingpackaging of food items and concrete classes implementing the Packinginterface as burgerwould be packed in wrapper and cold drink would be packed as bottle.

    We then create a Mealclass havingArrayListofItem and a MealBuilderto build different typesofMealobject by combining Item. BuilderPatternDemo, our demo class will use MealBuildertobuild a Meal.

    CHAPTER

    5

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    26/169

    TUTORIALS POINT

    Simply Easy Learning Page 19

    Class Diagram

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    27/169

    TUTORIALS POINT

    Simply Easy Learning Page 20

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1Create an interface Item representing food item and packing.

    Item.java

    publicinterfaceItem{publicString name();publicPacking packing();publicfloat price();

    }

    Packing.java

    publicinterfacePacking{publicString pack();

    }

    Step 2Create concreate classes implementing the Packing interface.

    Wrapper.java

    publicclassWrapperimplementsPacking{

    @OverridepublicString pack(){

    return"Wrapper";}

    }

    Bottle.java

    publicclassBottleimplementsPacking{

    @OverridepublicString pack(){

    return"Bottle";}

    }

    Step 3Create abstract classes implementing the item interface providing default functionalities.

    Burger.java

    publicabstractclassBurgerimplementsItem{

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    28/169

    TUTORIALS POINT

    Simply Easy Learning Page 21

    @OverridepublicPacking packing(){

    returnnewWrapper();}

    @Overridepublicabstractfloat price();

    }

    ColdDrink.java

    publicabstractclassColdDrinkimplementsItem{

    @OverridepublicPacking packing(){

    returnnewBottle();}

    @Override

    publicabstractfloat price();}

    Step 4Create concrete classes extending Burger and ColdDrink classes

    VegBurger.java

    publicclassVegBurgerextendsBurger{

    @Overridepublicfloat price(){

    return25.0f;}

    @OverridepublicString name(){

    return"Veg Burger";}

    }

    ChickenBurger.java

    publicclassChickenBurgerextendsBurger{

    @Overridepublicfloat price(){

    return50.5f;}

    @OverridepublicString name(){

    return"Chicken Burger";}

    }

    Coke.java

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    29/169

    TUTORIALS POINT

    Simply Easy Learning Page 22

    publicclassCokeextendsColdDrink{

    @Overridepublicfloat price(){

    return30.0f;

    }

    @OverridepublicString name(){

    return"Coke";}

    }

    Pepsi.java

    publicclassPepsiextendsColdDrink{

    @Overridepublicfloat price(){

    return35.0f;

    }

    @OverridepublicString name(){

    return"Pepsi";}

    }

    Step 5Create a Meal class having Item objects defined above.

    Meal.javaimport java.util.ArrayList;import java.util.List;

    publicclassMeal{privateList items =newArrayList();

    publicvoid addItem(Item item){items.add(item);

    }

    publicfloat getCost(){float cost =0.0f;for(Item item : items){

    cost += item.price();}return cost;

    }

    publicvoid showItems(){for(Item item : items){

    System.out.print("Item : "+item.name());System.out.print(", Packing : "+item.packing().pack());System.out.println(", Price : "+item.price());

    }

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    30/169

    TUTORIALS POINT

    Simply Easy Learning Page 23

    }}

    Step 6Create a MealBuilder class, the actual builder class responsible to create Meal objects.

    MealBuilder.java

    publicclassMealBuilder{

    publicMeal prepareVegMeal (){Meal meal =newMeal();meal.addItem(newVegBurger());meal.addItem(newCoke());return meal;

    }

    publicMeal prepareNonVegMeal (){Meal meal =newMeal();meal.addItem(newChickenBurger());meal.addItem(newPepsi());return meal;

    }}

    Step 7BuiderPatternDemo uses MealBuider to demonstrate builder pattern.

    BuilderPatternDemo.java

    publicclassBuilderPatternDemo{publicstaticvoid main(String[] args){

    MealBuilder mealBuilder =newMealBuilder();

    Meal vegMeal = mealBuilder.prepareVegMeal();System.out.println("Veg Meal");vegMeal.showItems();System.out.println("Total Cost: "+vegMeal.getCost());

    Meal nonVegMeal = mealBuilder.prepareNonVegMeal();System.out.println("\n\nNon-Veg Meal");nonVegMeal.showItems();System.out.println("Total Cost: "+nonVegMeal.getCost());

    }}

    Step 8Verify the output.

    Veg Meal

    Item : Veg Burger, Packing : Wrapper, Price : 25.0

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    31/169

    TUTORIALS POINT

    Simply Easy Learning Page 24

    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

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    32/169

    TUTORIALS POINT

    Simply Easy Learning Page 25

    Prototype Design PatternThis section describes prototype pattern and its implementation.

    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 bestway to create an object.

    This pattern involves implementing a prototype interface which tells to create a clone of thecurrent object. This pattern is used when creation of object directly is costly. For example, aobject is to be created after a costly database operation. We can cache the object, returns itsclone on next request and update the database as as and when needed thus reducing databasecalls.

    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 andreturns their clone when requested.

    PrototypPatternDemo, our demo class will use ShapeCache class to get a Shape object.

    CHAPTER

    6

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    33/169

    TUTORIALS POINT

    Simply Easy Learning Page 26

    Class Diagram.

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    34/169

    TUTORIALS POINT

    Simply Easy Learning Page 27

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1

    Create an abstract class implementing Clonable interface.

    Shape.java

    publicabstractclassShapeimplementsCloneable{

    privateString id;protectedString type;

    abstractvoid draw();

    publicString getType(){return type;

    }

    publicString getId(){return id;

    }

    publicvoid setId(String id){this.id = id;

    }

    publicObject clone(){Object clone =null;try{

    clone =super.clone();}catch(CloneNotSupportedException e){

    e.printStackTrace();}return clone;

    }}

    Step 2Create concrete classes extending the above class.

    Rectangle.java

    publicclassRectangleextendsShape{

    publicRectangle(){type ="Rectangle";

    }

    @Overridepublicvoid draw(){

    System.out.println("Inside Rectangle::draw() method.");

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    35/169

    TUTORIALS POINT

    Simply Easy Learning Page 28

    }}

    Square.java

    publicclassSquareextendsShape{

    publicSquare(){type ="Square";

    }

    @Overridepublicvoid draw(){

    System.out.println("Inside Square::draw() method.");}

    }

    Circle.java

    publicclassCircleextendsShape{

    publicCircle(){type ="Circle";

    }

    @Overridepublicvoid 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;

    publicclassShapeCache{

    privatestaticHashtable shapeMap=newHashtable();

    publicstaticShape getShape(String shapeId){Shape cachedShape = shapeMap.get(shapeId);return(Shape) cachedShape.clone();

    }

    // for each shape run database query and create shape// shapeMap.put(shapeKey, shape);// for example, we are adding three shapespublicstaticvoid loadCache(){

    Circle circle =newCircle();circle.setId("1");shapeMap.put(circle.getId(),circle);

    Square square =newSquare();

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    36/169

    TUTORIALS POINT

    Simply Easy Learning Page 29

    square.setId("2");shapeMap.put(square.getId(),square);

    Rectangle rectangle =newRectangle();rectangle.setId("3");

    shapeMap.put(rectangle.getId(),rectangle);}

    }

    Step 4

    PrototypePatternDemo uses ShapeCache class to get clones of shapes stored in a Hashtable.

    PrototypePatternDemo.java

    publicclassPrototypePatternDemo{publicstaticvoid main(String[] args){

    ShapeCache.loadCache();

    Shape clonedShape =(Shape)ShapeCache.getShape("1");System.out.println("Shape : "+ clonedShape.getType());

    Shape clonedShape2 =(Shape)ShapeCache.getShape("2");System.out.println("Shape : "+ clonedShape2.getType());

    Shape clonedShape3 =(Shape)ShapeCache.getShape("3");System.out.println("Shape : "+ clonedShape3.getType());

    }}

    Step 5Verify the output.

    Shape : Circle

    Shape : Square

    Shape : Rectangle

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    37/169

    TUTORIALS POINT

    Simply Easy Learning Page 30

    Adapter Design PatternThis section describes adapter pattern and its implementation.

    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 twoindependent interfaces.

    This pattern involves a single class which is responsible to join functionalities of independent orincompatible interfaces. A real life example could be a case of card reader which acts as anadapter between memory card and a laptop. You plugins the memory card into card reader andcard 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 playerdevice can play mp3 files only and wants to use an advanced audio player capable of playing vlcand mp4 files.

    ImplementationWe've an interface MediaPlayerinterface and a concrete classAudioPlayerimplementingtheMediaPlayerinterface.AudioPlayercan play mp3 format audio files by default.

    We're having another interfaceAdvancedMediaPlayerand concrete classes implementingtheAdvancedMediaPlayerinterface.These classes can play vlc and mp4 format files.

    We want to makeAudioPlayerto play other formats as well. To attain this, we've created anadapter class MediaAdapterwhich implements the MediaPlayerinterface andusesAdvancedMediaPlayerobjects to play the required format.

    AudioPlayeruses the adapter class MediaAdapterpassing it the desired audio type withoutknowing the actual class which can play the desired format.AdapterPatternDemo, our demo

    class will useAudioPlayerclass to play various formats.

    CHAPTER

    7

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    38/169

    TUTORIALS POINT

    Simply Easy Learning Page 31

    Class Diagram

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    39/169

    TUTORIALS POINT

    Simply Easy Learning Page 32

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1Create interfaces for Media Player and Advanced Media Player.

    MediaPlayer.java

    publicinterfaceMediaPlayer{publicvoid play(String audioType,String fileName);

    }

    AdvancedMediaPlayer.java

    publicinterfaceAdvancedMediaPlayer{

    publicvoid playVlc(String fileName);publicvoid playMp4(String fileName);

    }

    Step 2

    Create concrete classes implementing theAdvancedMediaPlayerinterface.

    VlcPlayer.java

    publicclassVlcPlayerimplementsAdvancedMediaPlayer{@Overridepublicvoid playVlc(String fileName){

    System.out.println("Playing vlc file. Name: "+ fileName);}

    @Overridepublicvoid playMp4(String fileName){

    //do nothing}

    }

    Mp4Player.java

    publicclassMp4PlayerimplementsAdvancedMediaPlayer{

    @Override

    publicvoid playVlc(String fileName){//do nothing}

    @Overridepublicvoid playMp4(String fileName){

    System.out.println("Playing mp4 file. Name: "+ fileName);}

    }

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    40/169

    TUTORIALS POINT

    Simply Easy Learning Page 33

    Step 3

    Create adapter class implementing the MediaPlayerinterface.

    MediaAdapter.javapublicclassMediaAdapterimplementsMediaPlayer{

    AdvancedMediaPlayer advancedMusicPlayer;

    publicMediaAdapter(String audioType){

    if(audioType.equalsIgnoreCase("vlc")){advancedMusicPlayer =newVlcPlayer();

    }elseif(audioType.equalsIgnoreCase("mp4")){advancedMusicPlayer =newMp4Player();

    }}

    @Overridepublicvoid play(String audioType,String fileName){

    if(audioType.equalsIgnoreCase("vlc")){advancedMusicPlayer.playVlc(fileName);

    }elseif(audioType.equalsIgnoreCase("mp4")){advancedMusicPlayer.playMp4(fileName);

    }}

    }

    Step 4

    Create concrete class implementing the MediaPlayerinterface.

    AudioPlayer.java

    publicclassAudioPlayerimplementsMediaPlayer{MediaAdapter mediaAdapter;

    @Overridepublicvoid play(String audioType,String fileName){

    //inbuilt support to play mp3 music filesif(audioType.equalsIgnoreCase("mp3")){

    System.out.println("Playing mp3 file. Name: "+ fileName);}

    //mediaAdapter is providing support to play other fileformats

    elseif(audioType.equalsIgnoreCase("vlc")|| audioType.equalsIgnoreCase("mp4")){mediaAdapter =newMediaAdapter(audioType);mediaAdapter.play(audioType, fileName);

    }else{

    System.out.println("Invalid media. "+audioType +" format not supported");

    }}

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    41/169

    TUTORIALS POINT

    Simply Easy Learning Page 34

    }

    Step 5Use the AudioPlayer to play different types of audio formats.

    AdapterPatternDemo.java

    publicclassAdapterPatternDemo{publicstaticvoid main(String[] args){

    AudioPlayer audioPlayer =newAudioPlayer();

    audioPlayer.play("mp3","beyond the horizon.mp3");audioPlayer.play("mp4","alone.mp4");audioPlayer.play("vlc","far far away.vlc");audioPlayer.play("avi","mind me.avi");

    }

    }

    Step 6Verify the output.

    Playing mp3 file. Name: beyond the horizon.mp3

    Playing mp4 file. Name: alone.mp4

    Playing vlc file. Name: far far away.vlc

    Invalid media. avi format not supported

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    42/169

    TUTORIALS POINT

    Simply Easy Learning Page 35

    Bridge Design PatternThis section describes bridge pattern and its implementation.

    Bridge is used where we need to decouple an abstraction from its implementation so that thetwo can vary independently. This type of design pattern comes under structural pattern as thispattern decouples implementation class and abstract class by providing a bridge structurebetween them.

    This pattern involves an interface which acts as a bridge which makes the functionality ofconcrete classes independent from interface implementer classes. Both types of classes can bealtered structurally without affecting each other.

    We are demonstrating use of Bridge pattern via following example in which a circle can be drawnin different colors using same abstract class method but different bridge implementer classes.

    Implementation

    We've an interface DrawAPIinterface which is acting as a bridge implementer and concreteclasses RedCircle, GreenCircle implementing the DrawAPIinterface. Shape is an abstract classand will use object ofDrawAPI. BridgePatternDemo, our demo class will use Shape class todraw different colored circle.

    CHAPTER

    8

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    43/169

    TUTORIALS POINT

    Simply Easy Learning Page 36

    Class Diagram

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    44/169

    TUTORIALS POINT

    Simply Easy Learning Page 37

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1Create bridge implementer interface.

    DrawAPI.java

    publicinterfaceDrawAPI{publicvoid drawCircle(int radius,int x,int y);

    }

    Step 2Create concrete bridge implementer classes implementing the DrawAPIinterface.

    RedCircle.java

    publicclassRedCircleimplementsDrawAPI{@Overridepublicvoid drawCircle(int radius,int x,int y){

    System.out.println("Drawing Circle[ color: red, radius: "+ radius +", x: "+x+", "+ y +"]");

    }}

    GreenCircle.java

    publicclassGreenCircleimplementsDrawAPI{@Overridepublicvoid 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 DrawAPIinterface.

    Shape.java

    publicabstractclassShape{protectedDrawAPI drawAPI;protectedShape(DrawAPI drawAPI){

    this.drawAPI = drawAPI;}publicabstractvoid draw();

    }

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    45/169

    TUTORIALS POINT

    Simply Easy Learning Page 38

    Step 4

    Create concrete class implementing the Shape interface.

    Circle.java

    publicclassCircleextendsShape{privateint x, y, radius;

    publicCircle(int x,int y,int radius,DrawAPI drawAPI){super(drawAPI);this.x = x;this.y = y;this.radius = radius;

    }

    publicvoid draw(){drawAPI.drawCircle(radius,x,y);

    }}

    Step 5

    Use the Shape and DrawAPIclasses to draw different colored circles.

    BridgePatternDemo.java

    publicclassBridgePatternDemo{publicstaticvoid main(String[] args){

    Shape redCircle =newCircle(100,100,10,newRedCircle());

    Shape greenCircle =newCircle(100,100,10,newGreenCircle());

    redCircle.draw();greenCircle.draw();

    }}

    Step 6Verify the output.

    Drawing Circle[ color: red, radius: 10, x: 100, 100]

    Drawing Circle[ color: green, radius: 10, x: 100, 100]

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    46/169

    TUTORIALS POINT

    Simply Easy Learning Page 39

    Filter Design PatternThis section describes filter pattern and its implementation.

    Filter pattern or Criteria pattern is a design pattern that enables developers to filter a set ofobjects, 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 multiplecriteria to obtain single criteria.

    Implementation

    We're going to create a Person object, Criteria interface and concrete classes implementing thisinterface to filter list ofPerson objects. CriteriaPatternDemo, our demo classuses Criteria objects to filter List ofPerson objects based on various criteria and theircombinations.

    CHAPTER

    9

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    47/169

    TUTORIALS POINT

    Simply Easy Learning Page 40

    Class Diagram

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    48/169

    TUTORIALS POINT

    Simply Easy Learning Page 41

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1Create a class on which criteria is to be applied.

    Person.java

    publicclassPerson{

    privateString name;privateString gender;privateString maritalStatus;

    publicPerson(String name,String gender,String maritalStatus){

    this.name = name;this.gender = gender;this.maritalStatus = maritalStatus;

    }

    publicString getName(){return name;

    }publicString getGender(){

    return gender;}publicString getMaritalStatus(){

    return maritalStatus;}

    }

    Step 2Create an interface for Criteria.

    Criteria.java

    import java.util.List;

    publicinterfaceCriteria{publicList meetCriteria(List persons);

    }

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    49/169

    TUTORIALS POINT

    Simply Easy Learning Page 42

    Step 3

    Create concrete classes implementing the Criteria interface.

    CriteriaMale.javaimport java.util.ArrayList;import java.util.List;

    publicclassCriteriaMaleimplementsCriteria{

    @OverridepublicList meetCriteria(List persons){

    List malePersons =newArrayList();for(Person person : persons){

    if(person.getGender().equalsIgnoreCase("MALE")){malePersons.add(person);

    }}return malePersons;

    }}

    CriteriaFemale.java

    import java.util.ArrayList;import java.util.List;

    publicclassCriteriaFemaleimplementsCriteria{

    @OverridepublicList meetCriteria(List persons){

    List femalePersons =newArrayList();for(Person person : persons){

    if(person.getGender().equalsIgnoreCase("FEMALE")){femalePersons.add(person);

    }}return femalePersons;

    }}

    CriteriaSingle.java

    import java.util.ArrayList;import java.util.List;

    publicclassCriteriaSingleimplementsCriteria{

    @OverridepublicList meetCriteria(List persons){

    List singlePersons =newArrayList();for(Person person : persons){

    if(person.getMaritalStatus().equalsIgnoreCase("SINGLE")){singlePersons.add(person);

    }}return singlePersons;

    }}

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    50/169

    TUTORIALS POINT

    Simply Easy Learning Page 43

    AndCriteria.java

    import java.util.List;

    publicclassAndCriteriaimplementsCriteria{

    privateCriteria criteria;privateCriteria otherCriteria;

    publicAndCriteria(Criteria criteria,Criteria otherCriteria){this.criteria = criteria;this.otherCriteria = otherCriteria;

    }

    @OverridepublicList meetCriteria(List persons){

    List firstCriteriaPersons =criteria.meetCriteria(persons);

    return otherCriteria.meetCriteria(firstCriteriaPersons);}

    }

    OrCriteria.java

    import java.util.List;

    publicclassAndCriteriaimplementsCriteria{

    privateCriteria criteria;privateCriteria otherCriteria;

    publicAndCriteria(Criteria criteria,Criteria otherCriteria){this.criteria = criteria;this.otherCriteria = otherCriteria;

    }

    @OverridepublicList meetCriteria(List persons){

    List firstCriteriaItems = criteria.meetCriteria(persons);List otherCriteriaItems =

    otherCriteria.meetCriteria(persons);

    for(Person person : otherCriteriaItems){if(!firstCriteriaItems.contains(person)){

    firstCriteriaItems.add(person);}

    }return firstCriteriaItems;

    }}

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    51/169

    TUTORIALS POINT

    Simply Easy Learning Page 44

    Step 4Use different Criteria and their combination to filter out persons.

    CriteriaPatternDemo.javapublicclassCriteriaPatternDemo{

    publicstaticvoid main(String[] args){List persons =newArrayList();

    persons.add(newPerson("Robert","Male","Single"));persons.add(newPerson("John","Male","Married"));persons.add(newPerson("Laura","Female","Married"));persons.add(newPerson("Diana","Female","Single"));persons.add(newPerson("Mike","Male","Single"));persons.add(newPerson("Bobby","Male","Single"));

    Criteria male =newCriteriaMale();Criteria female =newCriteriaFemale();

    Criteria single =newCriteriaSingle();Criteria singleMale =newAndCriteria(single, male);Criteria singleOrFemale =newOrCriteria(single, female);

    System.out.println("Males: ");printPersons(male.meetCriteria(persons));

    System.out.println("\nFemales: ");printPersons(female.meetCriteria(persons));

    System.out.println("\nSingle Males: ");printPersons(singleMale.meetCriteria(persons));

    System.out.println("\nSingle Or Females: ");printPersons(singleOrFemale.meetCriteria(persons));

    }

    publicstaticvoid printPersons(List persons){for(Person person : persons){

    System.out.println("Person : [ Name : "+ person.getName()+", Gender : "+ person.getGender()+", Marital Status : "+ person.getMaritalStatus()+" ]");

    }}

    }

    Step 5Verify the output.

    Males:

    Person : [ Name : Robert, Gender : Male, Marital Status : Single ]

    Person : [ Name : John, Gender : Male, Marital Status : Married ]

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    52/169

    TUTORIALS POINT

    Simply Easy Learning Page 45

    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 ]

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    53/169

    TUTORIALS POINT

    Simply Easy Learning Page 46

    Composite Design PatternThis section describes composite pattern and its implementation.

    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 wellas whole hierarchies. This type of design pattern comes under structural pattern as this patterncreates a tree structure of group of objects.

    This pattern creates a class contains group of its own objects. This class provides ways tomodify its group of same objects.

    We are demonstrating use of Composite pattern via following example in which show employeeshierarchy 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 allemployees.

    CHAPTER

    10

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    54/169

    TUTORIALS POINT

    Simply Easy Learning Page 47

    Class Diagram

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    55/169

    TUTORIALS POINT

    Simply Easy Learning Page 48

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1

    Create Employee class having list ofEmployee objects.

    Employee.java

    import java.util.ArrayList;import java.util.List;

    publicclassEmployee{privateString name;privateString dept;privateint salary;

    privateList subordinates;

    // constructorpublicEmployee(String name,String dept,int sal){

    this.name = name;this.dept = dept;this.salary = salary;subordinates =newArrayList();

    }

    publicvoid add(Employee e){subordinates.add(e);

    }

    publicvoid remove(Employee e){

    subordinates.remove(e);}

    publicList getSubordinates(){return subordinates;

    }

    publicString toString(){

    return("Employee :[ Name : "+ name+", dept : "+ dept +", salary :"+ salary+" ]");

    }}

    Step 2

    Use the Employee class to create and print employee hierarchy.

    CompositePatternDemo.java

    publicclassCompositePatternDemo{publicstaticvoid main(String[] args){

    Employee CEO =newEmployee("John","CEO",30000);

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    56/169

    TUTORIALS POINT

    Simply Easy Learning Page 49

    Employee headSales =newEmployee("Robert","Head Sales",20000);

    Employee headMarketing =newEmployee("Michel","Head

    Marketing",20000);

    Employee clerk1 =newEmployee("Laura","Marketing",10000);Employee clerk2 =newEmployee("Bob","Marketing",10000);

    Employee salesExecutive1 =newEmployee("Richard","Sales",10000);

    Employee salesExecutive2 =newEmployee("Rob","Sales",10000);

    CEO.add(headSales);CEO.add(headMarketing);

    headSales.add(salesExecutive1);headSales.add(salesExecutive2);

    headMarketing.add(clerk1);headMarketing.add(clerk2);

    //print all employees of the organizationSystem.out.println(CEO);for(Employee headEmployee : CEO.getSubordinates()){

    System.out.println(headEmployee);for(Employee employee : headEmployee.getSubordinates()){

    System.out.println(employee);}

    }}

    }

    Step 3Verify 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 ]

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    57/169

    TUTORIALS POINT

    Simply Easy Learning Page 50

    Decorator Design PatternThis section describes decorator pattern and its implementation.

    Decorator pattern allows adding new functionality an existing object without altering its

    structure. This type of design pattern comes under structural pattern as this pattern acts as awrapper to existing class.

    This pattern creates a decorator class which wraps the original class and provides additionalfunctionality keeping class methods signature intact.

    We are demonstrating use of Decorator pattern via following example in which we'll decorate ashape 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 ShapeDecoratorimplementing the Shape interfaceand havingShape object as its instance variable.

    RedShapeDecoratoris concrete class implementing ShapeDecorator.

    DecoratorPatternDemo, our demo class will use RedShapeDecoratorto decorate Shape objects.

    CHAPTER

    11

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    58/169

    TUTORIALS POINT

    Simply Easy Learning Page 51

    Class Diagram

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    59/169

    TUTORIALS POINT

    Simply Easy Learning Page 52

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1Create an interface.

    Shape.java

    publicinterfaceShape{void draw();

    }

    Step 2Create concrete classes implementing the same interface.

    Rectangle.java

    publicclassRectangleimplementsShape{

    @Overridepublicvoid draw(){

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

    }

    Circle.java

    publicclassCircleimplementsShape{

    @Overridepublicvoid draw(){

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

    }

    Step 3

    Create abstract decorator class implementing theShapeinterface.

    ShapeDecorator.javapublicabstractclassShapeDecoratorimplementsShape{

    protectedShape decoratedShape;

    publicShapeDecorator(Shape decoratedShape){this.decoratedShape = decoratedShape;

    }

    publicvoid draw(){decoratedShape.draw();

    }

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    60/169

    TUTORIALS POINT

    Simply Easy Learning Page 53

    }

    Step 4Create concrete decorator class extending theShapeDecoratorclass.

    RedShapeDecorator.java

    publicclassRedShapeDecoratorextendsShapeDecorator{

    publicRedShapeDecorator(Shape decoratedShape){super(decoratedShape);

    }

    @Overridepublicvoid draw(){

    decoratedShape.draw();

    setRedBorder(decoratedShape);}

    privatevoid setRedBorder(Shape decoratedShape){System.out.println("Border Color: Red");

    }}

    Step 5

    Use theRedShapeDecoratorto decorateShapeobjects.

    DecoratorPatternDemo.java

    publicclassDecoratorPatternDemo{publicstaticvoid main(String[] args){

    Shape circle =newCircle();

    Shape redCircle =newRedShapeDecorator(newCircle());

    Shape redRectangle =newRedShapeDecorator(newRectangle());System.out.println("Circle with normal border");circle.draw();

    System.out.println("\nCircle of red border");redCircle.draw();

    System.out.println("\nRectangle of red border");redRectangle.draw();

    }}

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    61/169

    TUTORIALS POINT

    Simply Easy Learning Page 54

    Step 6

    Verify the output.

    Circle with normal border

    Shape: Circle

    Circle of red border

    Shape: Circle

    Border Color: Red

    Rectangle of red borderShape: Rectangle

    Border Color: Red

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    62/169

    TUTORIALS POINT

    Simply Easy Learning Page 55

    Faade Design PatternThis section describes facade pattern and its implementation.

    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 structuralpattern 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 byclient 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 ShapeMakeris defined as a next step.

    ShapeMakerclass uses the concrete classes to delegates user calls to theseclasses.FacadePatternDemo, our demo class will use ShapeMakerclass to show the results.

    CHAPTER

    12

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    63/169

    TUTORIALS POINT

    Simply Easy Learning Page 56

    Class Diagram

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    64/169

    TUTORIALS POINT

    Simply Easy Learning Page 57

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1Create an interface.

    Shape.java

    publicinterfaceShape{void draw();

    }

    Step 2Create concrete classes implementing the same interface.

    Rectangle.java

    publicclassRectangleimplementsShape{

    @Overridepublicvoid draw(){

    System.out.println("Rectangle::draw()");}

    }

    Square.java

    publicclassSquareimplementsShape{

    @Overridepublicvoid draw(){

    System.out.println("Square::draw()");}

    }

    Circle.java

    publicclassCircleimplementsShape{

    @Overridepublicvoid draw(){

    System.out.println("Circle::draw()");}

    }

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    65/169

    TUTORIALS POINT

    Simply Easy Learning Page 58

    Step 3Create a facade class.

    ShapeMaker.javapublicclassShapeMaker{

    privateShape circle;privateShape rectangle;privateShape square;

    publicShapeMaker(){circle =newCircle();rectangle =newRectangle();square =newSquare();

    }

    publicvoid drawCircle(){circle.draw();

    }

    publicvoid drawRectangle(){rectangle.draw();

    }publicvoid drawSquare(){

    square.draw();}

    }

    Step 4Use the facade to draw various types of shapes.

    FacadePatternDemo.java

    publicclassFacadePatternDemo{publicstaticvoid main(String[] args){

    ShapeMaker shapeMaker =newShapeMaker();

    shapeMaker.drawCircle();shapeMaker.drawRectangle();shapeMaker.drawSquare();

    }}

    Step 5Verify the output.

    Circle::draw()

    Rectangle::draw()

    Square::draw()

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    66/169

    TUTORIALS POINT

    Simply Easy Learning Page 59

    Flyweight Design PatternThis section describes flyweight pattern and its implementation.

    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 structuralpattern as this pattern provides ways to decrease objects count thus improving applicationrequired objects structure.

    Flyweight pattern try to reuse already existing similar kind objects by storing them and createsnew object when no matching object is found. We'll demonstrate this pattern by drawing 20 circleof different locations but we'll creating only 5 objects. Only 5 colors are available so colorproperty 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 ShapeFactoryis defined as a next step.

    ShapeFactoryhave a HashMap ofCircle having key as color of the Circle object. Whenever arequest comes to create a circle of particular color to ShapeFactory. ShapeFactorychecks thecircle object in itsHashMap, if object ofCircle found, that object is returned otherwise a newobject is created, stored in hashmap for future use and returned to client.

    FlyWeightPatternDemo, our demo class will use ShapeFactoryto get a Shape object. It will passinformation (red / green / blue/ black / white) to ShapeFactoryto get the circle of desired color itneeds.

    CHAPTER

    13

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    67/169

    TUTORIALS POINT

    Simply Easy Learning Page 60

    Class Diagram

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    68/169

    TUTORIALS POINT

    Simply Easy Learning Page 61

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1Create an interface.

    Shape.java

    publicinterfaceShape{void draw();

    }

    Step 2Create concrete class implementing the same interface.

    Circle.java

    publicclassCircleimplementsShape{privateString color;privateint x;privateint y;privateint radius;

    publicCircle(String color){this.color = color;

    }

    publicvoid setX(int x){this.x = x;

    }

    publicvoid setY(int y){this.y = y;

    }

    publicvoid setRadius(int radius){this.radius = radius;

    }

    @Overridepublicvoid draw(){

    System.out.println("Circle: Draw() [Color : "+ color+", x : "+ x +", y :"+ y +", radius :"+ radius);}

    }

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    69/169

    TUTORIALS POINT

    Simply Easy Learning Page 62

    Step 3Create a Factory to generate object of concrete class based on given information.

    ShapeFactory.javaimport java.util.HashMap;

    publicclassShapeFactory{privatestaticfinalHashMap circleMap =new

    HashMap();

    publicstaticShape getCircle(String color){Circle circle =(Circle)circleMap.get(color);

    if(circle ==null){circle =newCircle(color);circleMap.put(color, circle);System.out.println("Creating circle of color : "+ color);

    }

    return circle;}

    }

    Step 4Use the Factory to get object of concrete class by passing an information such as color.

    FlyweightPatternDemo.java

    publicclassFlyweightPatternDemo{privatestaticfinalString colors[]=

    {"Red","Green","Blue","White","Black"};publicstaticvoid main(String[] args){

    for(int i=0; i

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    70/169

    TUTORIALS POINT

    Simply Easy Learning Page 63

    Step 5Verify 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

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    71/169

    TUTORIALS POINT

    Simply Easy Learning Page 64

    Proxy Design PatternThis section describes proxy pattern and its implementation.

    In Proxy pattern, a class represents functionality of another class. This type of design pattern

    comes under structural pattern.

    In Proxy pattern, we create object having original object to interface its functionality to outerworld.

    Implementation

    We're going to create a Image interface and concrete classes implementingthe Image interface.ProxyImage is a a proxy class to reduce memory footprintofRealImage object loading.

    ProxyPatternDemo, our demo class will use ProxyImage to get a Image object to load anddisplay as it needs.

    CHAPTER

    14

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    72/169

    TUTORIALS POINT

    Simply Easy Learning Page 65

    Class Diagram

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    73/169

    TUTORIALS POINT

    Simply Easy Learning Page 66

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1Create an interface.

    Image.java

    publicinterfaceImage{void display();

    }

    Step 2Create concrete classes implementing the same interface.

    RealImage.java

    publicclassRealImageimplementsImage{

    privateString fileName;

    publicRealImage(String fileName){this.fileName = fileName;loadFromDisk(fileName);

    }

    @Overridepublicvoid display(){System.out.println("Displaying "+ fileName);

    }

    privatevoid loadFromDisk(String fileName){System.out.println("Loading "+ fileName);

    }}

    ProxyImage.java

    publicclassProxyImageimplementsImage{

    privateRealImage realImage;

    privateString fileName;

    publicProxyImage(String fileName){this.fileName = fileName;

    }

    @Overridepublicvoid display(){

    if(realImage ==null){realImage =newRealImage(fileName);

    }

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    74/169

    TUTORIALS POINT

    Simply Easy Learning Page 67

    realImage.display();}

    }

    Step 3

    Use theProxyImageto get object ofRealImageclass when required.

    ProxyPatternDemo.java

    publicclassProxyPatternDemo{

    publicstaticvoid main(String[] args){Image image =newProxyImage("test_10mb.jpg");

    //image will be loaded from diskimage.display();

    System.out.println("");//image will not be loaded from diskimage.display();

    }}

    Step 4Verify the output.

    Loading test_10mb.jpg

    Displaying test_10mb.jpg

    Displaying test_10mb.jpg

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    75/169

    TUTORIALS POINT

    Simply Easy Learning Page 68

    Chain of Responsibility Design PatternThis section describes chain of responsibility pattern and its implementation.

    As the name suggest, the chain of responsibility pattern creates a chain of receiver objects fora 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 objectcannot handle the request then it passes the same to the next receiver and so on.

    Implementation

    We've created an abstract classAbstractLoggerwith a level of logging. Then we've created threetypes of loggers extending theAbstractLogger.

    Each logger checks the level of message to its level and print accordingly otherwise does notprint and pass the message to its next logger.

    CHAPTER

    15

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    76/169

    TUTORIALS POINT

    Simply Easy Learning Page 69

    Class Diagram

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    77/169

    TUTORIALS POINT

    Simply Easy Learning Page 70

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1Create an abstract logger class.

    AbstractLogger.java

    publicabstractclassAbstractLogger{publicstaticint INFO =1;publicstaticint DEBUG =2;publicstaticint ERROR =3;

    protectedint level;

    //next element in chain or responsibilityprotectedAbstractLogger nextLogger;

    publicvoid setNextLogger(AbstractLogger nextLogger){this.nextLogger = nextLogger;

    }

    publicvoid logMessage(int level,String message){if(this.level

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    78/169

    TUTORIALS POINT

    Simply Easy Learning Page 71

    ErrorLogger.java

    publicclassErrorLoggerextendsAbstractLogger{

    publicErrorLogger(int level){

    this.level = level;}

    @Overrideprotectedvoid write(String message){

    System.out.println("Error Console::Logger: "+ message);}

    }

    FileLogger.java

    publicclassFileLoggerextendsAbstractLogger{

    publicFileLogger(int level){this.level = level;

    }

    @Overrideprotectedvoid write(String message){

    System.out.println("File::Logger: "+ message);}

    }

    Step 3Create 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

    publicclassChainPatternDemo{

    privatestaticAbstractLogger getChainOfLoggers(){

    AbstractLogger errorLogger =newErrorLogger(AbstractLogger.ERROR);

    AbstractLogger fileLogger =newFileLogger(AbstractLogger.DEBUG);AbstractLogger consoleLogger =new

    ConsoleLogger(AbstractLogger.INFO);

    errorLogger.setNextLogger(fileLogger);fileLogger.setNextLogger(consoleLogger);

    return errorLogger;}

    publicstaticvoid main(String[] args){AbstractLogger loggerChain = getChainOfLoggers();

    loggerChain.logMessage(AbstractLogger.INFO,

    "This is an information.");

    loggerChain.logMessage(AbstractLogger.DEBUG,

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    79/169

    TUTORIALS POINT

    Simply Easy Learning Page 72

    "This is an debug level information.");

    loggerChain.logMessage(AbstractLogger.ERROR,

    "This is an error information.");}

    }

    Step 4Verify 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.

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    80/169

    TUTORIALS POINT

    Simply Easy Learning Page 73

    Command Design PatternThis section describes command pattern and its implementation.

    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 objectlooks for the appropriate object which can handle this command and pass the command to thecorresponding object and that object executes the command.

    Implementation

    We've created an interface Orderwhich is acting as a command. We've created a Stockclasswhich acts as a request.

    We've concrete command classes BuyStockand SellStockimplementing Orderinterface whichwill do actual command processing. A class Brokeris created which acts as a invoker object. Itcan take order and place orders.

    Brokerobject uses command pattern to identify which object will execute which command basedon type of command. CommandPatternDemo, our demo class will use Brokerclass todemonstrate command pattern.

    CHAPTER

    16

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    81/169

    TUTORIALS POINT

    Simply Easy Learning Page 74

    Class Diagram

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    82/169

    TUTORIALS POINT

    Simply Easy Learning Page 75

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1Create a command interface.

    Order.java

    publicinterfaceOrder{void execute();

    }

    Step 2Create a request class.

    Stock.java

    publicclassStock{

    privateString name ="ABC";privateint quantity =10;

    publicvoid buy(){System.out.println("Stock [ Name: "+name+",

    Quantity: "+ quantity +" ] bought");}publicvoid sell(){

    System.out.println("Stock [ Name: "+name+",Quantity: "+ quantity +" ] sold");

    }}

    Step 3

    Create concrete classes implementing theOrderinterface.

    BuyStock.java

    publicclassBuyStockimplementsOrder{privateStock abcStock;

    publicBuyStock(Stock abcStock){this.abcStock = abcStock;

    }

    publicvoid execute(){abcStock.buy();

    }}

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    83/169

    TUTORIALS POINT

    Simply Easy Learning Page 76

    SellStock.java

    publicclassSellStockimplementsOrder{privateStock abcStock;

    publicSellStock(Stock abcStock){

    this.abcStock = abcStock;}

    publicvoid execute(){abcStock.sell();

    }}

    Step 4Create command invoker class.

    Broker.javaimport java.util.ArrayList;import java.util.List;

    publicclassBroker{privateList orderList =newArrayList();

    publicvoid takeOrder(Order order){orderList.add(order);

    }

    publicvoid placeOrders(){for(Order order : orderList){

    order.execute();}orderList.clear();

    }}

    Step 5Use the Broker class to take and execute commands.

    CommandPatternDemo.java

    publicclassCommandPatternDemo{publicstaticvoid main(String[] args){

    Stock abcStock =newStock();

    BuyStock buyStockOrder =newBuyStock(abcStock);SellStock sellStockOrder =newSellStock(abcStock);

    Broker broker =newBroker();broker.takeOrder(buyStockOrder);broker.takeOrder(sellStockOrder);

    broker.placeOrders();}

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    84/169

    TUTORIALS POINT

    Simply Easy Learning Page 77

    }

    Step 6Verify the output.

    Stock [ Name: ABC, Quantity: 10 ] bought

    Stock [ Name: ABC, Quantity: 10 ] sold

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    85/169

    TUTORIALS POINT

    Simply Easy Learning Page 78

    Interpreter Design PatternThis section describes interpreter pattern and its implementation.

    Interpreter pattern provides way to evaluate language grammar or expression. This type of

    pattern comes under behavioral patterns. This pattern involves implementing an expressioninterface which tells to interpret a particular context. This pattern is used in SQL parsing, symbolprocessing engine etc.

    Implementation

    We're going to create an interface Expression and concrete classes implementingthe Expressioninterface. A class TerminalExpression is defined which acts as a main interpreterof context in question. Other classes OrExpression,AndExpression are used to createcombinational expressions.

    InterpreterPatternDemo, our demo class will use Expression class to create rules anddemonstrate parsing of expressions.

    CHAPTER

    17

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    86/169

    TUTORIALS POINT

    Simply Easy Learning Page 79

    Class Diagram

  • 7/22/2019 Java Design Pattern Tutorial for java expert

    87/169

    TUTORIALS POINT

    Simply Easy Learning Page 80

    Steps

    Use the following steps to implement the above mentioned design pattern.

    Step 1Create an expression interface.

    Expression.java

    publicinterfaceExpression{publicboolean interpret(String context);

    }

    Step 2Create concrete classes implementing the above interface.

    TerminalExpression.java

    publicclassTerminalExpressionimplementsExpression{

    privateString data;

    publicTerminalExpression(String data){this.data = data;

    }

    @Overridepublicboolean interpret(String context){

    if(context.contains(data)){returntrue;

    }returnfalse;

    }}

    OrExpression.java

    publicclassOrExpressionimplementsExpression{

    privateExpression expr1 =null;privateExpression expr2 =null;

    publicOrExpression(Expression expr1,Expression expr2){this.expr1 = expr1;this.expr2 = expr2;

    }

    @Ove