Java Design Pattern eBook

download Java Design Pattern eBook

of 132

Transcript of Java Design Pattern eBook

  • 8/10/2019 Java Design Pattern eBook

    1/132

  • 8/10/2019 Java Design Pattern eBook

    2/132

    !#$%&'()*+,-.$/ 0(1+ "$2 "#$

    %&'() *+ ,*-.)-.Creational Design Patterns .................................................................................................. 5

    1. Singleton Pattern ......................................................................................................... 6A. Eager Initialization ................................................................................................. 7

    B. Static block initialization ........................................................................................ 7C. Lazy Initialization .................................................................................................. 8D. Thread Safe Singleton ............................................................................................ 9E. Bill Pugh Singleton Implementation .................................................................... 10F. Using Reflection to destroy Singleton Pattern...................................................... 11G. Enum Singleton .................................................................................................... 12H. Serialization and Singleton .................................................................................. 12

    2. Factory Pattern .......................................................................................................... 15A. Super Class ........................................................................................................... 15B. Sub Classes ........................................................................................................... 15C. Factory Class ........................................................................................................ 17

    D. Benefits of Factory Pattern .................................................................................. 19E. Factory Pattern Examples in JDK ........................................................................ 19

    3. Abstract Factory Pattern ........................................................................................... 20A. Super Class and Sub-Classes ............................................................................... 20B. Factory Classes for Each sub-class ...................................................................... 22B. Benefits of Abstract Factory Pattern .................................................................... 25C. Abstract Factory Pattern Examples in JDK.......................................................... 25

    4. Builder Pattern .......................................................................................................... 26A. Builder Pattern Implementation ........................................................................... 26B. Builder Design Pattern Example in JDK.............................................................. 29

    5. Prototype Pattern ....................................................................................................... 30

    Structural Design Patterns................................................................................................. 331. Adapter Design Pattern ............................................................................................. 33

    A. Two Way Adapter Pattern .................................................................................... 34B. Class Adapter Implementation ............................................................................. 34C. Object Adapter Implementation ........................................................................... 35D. Adapter Pattern Class Diagram ............................................................................ 37E. Adapter Pattern Example in JDK ........................................................................ 38

    2. Composite Pattern ..................................................................................................... 39A. Base Component .................................................................................................. 39B. Leaf Objects ......................................................................................................... 40C. Composite............................................................................................................. 40

    D. Important Points about Composite Pattern .......................................................... 433. Proxy Pattern ............................................................................................................. 44

    A. Main Class............................................................................................................ 44B. Proxy Class ........................................................................................................... 45C. Proxy Pattern Client Test Program....................................................................... 46

    4. Flyweight Pattern ...................................................................................................... 47A. Flyweight Interface and Concrete Classes ........................................................... 48B. Flyweight Factory ................................................................................................ 49

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    3/132

    !#$%&'()*+,-.$/ 0(1+ $$2 "#$

    C. Flyweight Pattern Client Example ....................................................................... 50D. Flyweight Pattern Example in JDK ..................................................................... 54E. Important Points ................................................................................................... 54

    5. Facade Pattern ........................................................................................................... 55A. Set of Interfaces ................................................................................................... 55

    B. Facade Interface ................................................................................................... 56C. Client Program ..................................................................................................... 58D. Important Points ................................................................................................... 59

    6. Bridge Pattern ........................................................................................................... 607. Decorator Pattern ...................................................................................................... 64

    A. Component Interface ............................................................................................ 65B. Component Implementation ................................................................................. 65C. Decorator .............................................................................................................. 66D: Concrete Decorators............................................................................................. 66D. Decorator Pattern Class Diagram ......................................................................... 67E. Decorator Pattern Client Program ........................................................................ 68

    F. Important Points.................................................................................................... 68Behavioral Design Patterns ............................................................................................... 69

    1. Template Method Pattern .......................................................................................... 69A. Template Method Abstract Class ......................................................................... 69B. Template Method Concrete Classes ..................................................................... 70C. Template Method Pattern Client .......................................................................... 71D. Template Method Class Diagram ........................................................................ 72E. Template Method Pattern in JDK ......................................................................... 73F. Important Points.................................................................................................... 73

    2. Mediator Pattern........................................................................................................ 74A. Mediator Interface ................................................................................................ 75

    B. Colleague Interface .............................................................................................. 75C. Concrete Mediator ................................................................................................ 76C. Concrete Colleague .............................................................................................. 76D. Mediator Pattern Client ........................................................................................ 77E. Mediator Pattern Class Diagram .......................................................................... 78G. Important Points ................................................................................................... 78

    3. Chain of Responsibility Pattern ................................................................................ 79A. Base Classes and Interface ................................................................................... 80B. Concrete Chain Implementations ......................................................................... 81C. Creating the Chain ................................................................................................ 83D. Class Diagram ...................................................................................................... 85

    E. Chain of Responsibility Pattern Examples in JDK............................................... 85F. Important Points.................................................................................................... 854. Observer Pattern........................................................................................................ 87

    A. Observer Pattern Example ................................................................................... 88B. Observer Pattern Class Diagram .......................................................................... 93

    5. Strategy Pattern ......................................................................................................... 94A. Strategy Pattern Class Diagram ........................................................................... 98B. Important Points ................................................................................................... 98

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    4/132

    !#$%&'()*+,-.$/ 0(1+ #$2 "#$

    6. Command Pattern...................................................................................................... 99A. Receiver Classes .................................................................................................. 99B. Command Interface and Implementations ......................................................... 101C. Invoker Class ...................................................................................................... 102C. Class Diagram .................................................................................................... 104

    D. Command Pattern JDK Example ....................................................................... 105E. Important Points ................................................................................................. 1057. State Pattern ............................................................................................................ 107

    A. State Interface .................................................................................................... 108B. Concrete State Implementations......................................................................... 108C. Context Implementation ..................................................................................... 109D. Test Program ...................................................................................................... 110

    8. Visitor Pattern ......................................................................................................... 111A. Visitor Pattern Class Diagram............................................................................ 114

    9. Interpreter Pattern ................................................................................................... 116A. Class Diagram .................................................................................................... 119

    B. Important Points ................................................................................................. 11910. Iterator Pattern ...................................................................................................... 120A. Iterator Pattern in JDK ....................................................................................... 125B. Important Points ................................................................................................. 125

    11. Memento Pattern ................................................................................................... 126A. Originator Class ................................................................................................. 126B. Caretaker Class ................................................................................................... 127C. Memento Test Class ........................................................................................... 128

    Copyright Notice ......................................................................................................... 130References ................................................................................................................... 131

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    5/132

    !#$%&'()*+,-.$/ 0(1+ /$2 "#$

    0)123- 4&..)5-1 67)572)8Design Patternsare very popular among software developers. A design

    pattern is a well-described solution to a common software problem.

    Some of the benefits of using design patterns are:

    1. Design Patterns are already defined and provides industry standard

    approach to solve a recurring problem, so it saves time if we sensibly

    use the design pattern.

    2. Using design patterns promotes reusability that leads to

    more robust and highly maintainable code. It helps in reducing total

    cost of ownership (TCO) of the software product.

    3. Since design patterns are already defined, it makes our code easy to

    understand and debug. It leads to faster development and new

    members of team understand it easily.

    Java Design Patternsare divided into three categories creational, structural, and behavioraldesign patterns.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    6/132

    !#$%&'()*+,-.$/ 0(1+ 9$2 "#$

    ,5)&.2*-&( 0)123- 4&..)5-1

    Creational design patterns provide solution to instantiate an object in the bestpossible way for specific situations.

    The basic form of object creation could result in design problems or addunwanted complexity to the design. Creational design patterns solve this

    problem by controlling the object creation by different ways.

    There are five creational design patterns that we will discuss in this eBook.

    1. Singleton Pattern2. Factory Pattern3. Abstract Factory Pattern4. Builder Pattern5. Prototype Pattern

    All these patterns solve specific problems with object creation, so you

    should understand and use them when needed.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    7/132

    !#$%&'()*+,-.$/ 0(1+ :$2 "#$

    ";

  • 8/10/2019 Java Design Pattern eBook

    8/132

    !#$%&'()*+,-.$/ 0(1+ =$2 "#$

    >; ?&3)5 @-2.2&(2A&.2*-

    In eager initialization, the instance of Singleton Class is created at the time

    of class loading, this is the easiest method to create a singleton class but it

    has a drawback that instance is created even though client application might

    not be using it.

    Here is the implementation of static initialization singleton class.

    !"#$"%&"#$%'()*+,-.%/0)1+-2#)3

    !'()*##)"++,"%&-./*0*")*1&23*/%)&04/4

    !-*5"0&+0"0*#6*/")5*1-(6)020*+07-,80)1+-2#) 0)/2*)"- 9/&7

    5*1-(6)020*+07-,80)1+-2#):;3

    !'()*#+0"0*#5*1-(6)020*+07-,80)1+-2#) %&0./+0"/#&:;4

    -&0'-/0)/2*)"-3

    >

    >

    If your singleton class is not using a lot of resources, this is the approach touse. But in most of the scenarios, Singleton classes are created for resources

    such as File System, Database connections etc and we should avoid the

    instantiation until unless client calls the getInstance method. Also this

    method doesnt provide any options for exception handling.

    B;

  • 8/10/2019 Java Design Pattern eBook

    9/132

    !#$%&'()*+,-.$/ 0(1+ E$2 "#$

    !"#$"%&"#$%'()*+,-.%/0)1+-2#)3

    !'()*##)"++30"0*#8)4#$3*/%)&04/4

    !-*5"0&+0"0*#82*20"?+#"@80)1+-2#) 0)/2*)"-3

    !-*5"0&30"0*#8)4#$3*/%)&04/:;4>

  • 8/10/2019 Java Design Pattern eBook

    10/132

    !#$%&'()*+,-.$/ 0(1+ H$2 "#$

    !'()*#+0"0*#F*7G6)020*+07-,80)1+-2#) %&0./+0"/#&:;4

    *6:0)/2*)"- 99/'));4

    0)/2*)"- 9/&7F*7G6)020*+07-,80)1+-2#):;3

    >

    -&0'-/0)/2*)"-3>

    >

    The above implementation works fine in case of single threaded

    environment but when it comes to multithreaded systems, it can cause issues

    if multiple threads are inside the if loop at the same time. It will destroy the

    singleton pattern and both threads will get the different instances of

    singleton class. In next section, we will see different ways to create athread-

    safesingleton class.

    0; %I5)&J

    !'()*#+0"0*#+9/#:-4/*1&2HD(-*,8*B-80)1+-2#) %&0./+0"/#&:;4

    *6:0)/2*)"- 99/'));4

    0)/2*)"- 9/&7HD(-*,8*B-80)1+-2#):;3

    >-&0'-/0)/2*)"-3

    >

    >

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1061/java-synchronization-and-thread-safety-tutorial-with-exampleshttp://www.journaldev.com/1061/java-synchronization-and-thread-safety-tutorial-with-exampleshttp://www.journaldev.com/1061/java-synchronization-and-thread-safety-tutorial-with-exampleshttp://www.journaldev.com/1061/java-synchronization-and-thread-safety-tutorial-with-exampleshttp://www.journaldev.com/1061/java-synchronization-and-thread-safety-tutorial-with-exampleshttp://www.journaldev.com/1061/java-synchronization-and-thread-safety-tutorial-with-exampleshttp://www.journaldev.com/1061/java-synchronization-and-thread-safety-tutorial-with-exampleshttp://www.journaldev.com/1061/java-synchronization-and-thread-safety-tutorial-with-exampleshttp://www.journaldev.com/1061/java-synchronization-and-thread-safety-tutorial-with-exampleshttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    11/132

    !#$%&'()*+,-.$/ 0(1+ "K$2 "#$

    Above implementation works fine and provides thread-safety but it reducesthe performance because of cost associated with the synchronized method,although we need it only for the first few threads who might create theseparate instances (Read: Java Synchronization). To avoid this extraoverhead every time, double checked locking principle is used. In thisapproach, the synchronized block is used inside if condition with anadditional check to ensure that only one instance of singleton class iscreated.

    Below code snippet provides the double checked locking implementation.

    !'()*#+0"0*#HD(-*,8*B-80)1+-2#) %&0./+0"/#&@+*/%A4'()&>4#$*/%:;4

    *6:0)/2*)"- 99/'));4

    +9/#:-4/*1&2:HD(-*,8*B-80)1+-2#)%"+*//;4

    *6:0)/2*)"- 99/'));4

    0)/2*)"- 9/&7HD(-*,8*B-80)1+-2#):;3

    >

    >

    >

    -&0'-/0)/2*)"-3

    >

    ?; B2(( 4L3I

    !-*5"0&+0"0*##)"++3*/%)&04/C&)!&-4

    !-*5"0&+0"0*#6*/")?0++I'1D80)1+-2#) 6J8HKJL5 9/&7

    ?0++I'1D80)1+-2#):;3

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1061/java-synchronization-and-thread-safety-tutorial-with-exampleshttp://www.journaldev.com/1061/java-synchronization-and-thread-safety-tutorial-with-exampleshttp://www.journaldev.com/996/java-nested-classes-java-inner-class-static-nested-class-local-inner-class-and-anonymous-inner-classhttp://www.journaldev.com/996/java-nested-classes-java-inner-class-static-nested-class-local-inner-class-and-anonymous-inner-classhttp://www.journaldev.com/996/java-nested-classes-java-inner-class-static-nested-class-local-inner-class-and-anonymous-inner-classhttp://www.journaldev.com/996/java-nested-classes-java-inner-class-static-nested-class-local-inner-class-and-anonymous-inner-classhttp://www.journaldev.com/996/java-nested-classes-java-inner-class-static-nested-class-local-inner-class-and-anonymous-inner-classhttp://www.journaldev.com/996/java-nested-classes-java-inner-class-static-nested-class-local-inner-class-and-anonymous-inner-classhttp://www.journaldev.com/1061/java-synchronization-and-thread-safety-tutorial-with-exampleshttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    12/132

    !#$%&'()*+,-.$/ 0(1+ ""$2 "#$

    >

    !'()*#+0"0*#?0++I'1D80)1+-2#) %&0./+0"/#&:;4

    -&0'-/80)1+-2#)M-+=-(%6J8HKJL53

    >

    >

    Notice the private inner static class that contains the instance of thesingleton class. When the singleton class is loaded, SingletonHelper class isnot loaded into memory and only when someone calls the getInstancemethod, this class gets loaded and creates the Singleton class instance.

    This is the most widely used approach for Singleton class as it doesnt

    require synchronization. I am using this approach in many of my projects

    and its easy to understand and implement also.

    O; P12-3 Q)+()C.2*- .* J)1.5*G

    5*1-(6)020*+07-,80)1+-2#)%1-26)/2*)"-:;3

    5*1-(6)020*+07-,80)1+-2#) 0)/2*)"-HQ# 9/'))3

    0-94L#)/2('"2#(NO"#)/2('"2#(/ 9

    5*1-(6)020*+07-,80)1+-2#)%"+*//%1-2R-"+*(-,L#)/2('"2#(/:;3

    64-:L#)/2('"2#( "#)/2('"2#( S"#)/2('"2#(/;4

  • 8/10/2019 Java Design Pattern eBook

    13/132

    !#$%&'()*+,-.$/ 0(1+ "$$2 "#$

    (-&"$3

    >

    >#"0#::5C"-=20#) -;4

    -%=(0)282*"@H(*"-:;3

    >

    8G/2-$%#'2%=(0)2+):0)/2*)"-P)-%D*/DL#,-:;;38G/2-$%#'2%=(0)2+):0)/2*)"-HQ#%D*/DL#,-:;;3

    >

    >

    When you run the above test class, you will notice that hashCode of both theinstances are not same that destroys the singleton pattern. Reflection is very

    powerful and used in a lot of frameworks like Spring and Hibernate, docheck outJava Reflection Tutorial.

    R; ?-LM

  • 8/10/2019 Java Design Pattern eBook

    14/132

    !#$%&'()*+,-.$/ 0(1+ "#$2 "#$

    retrieve it at later point of time. Here is a small singleton class thatimplements Serializable interface also.

    !"#$"%&"#$%'()*+,-.%/0)1+-2#)3

    *

    !'()*##)"++3&-*")*1&23*/%)&04/*

    !-*5"0&+0"0*#6*/"))4/%/-(0*+T-(/0#)U6R 9VGHIJGHHKLMINGGLGNNO>3

    !-*5"0&3&-*")*1&23*/%)&04/:;4>

    !-*5"0&+0"0*##)"++3*/%)&04/C&)!&-4

    !-*5"0&+0"0*#6*/")8-(0*+07-,80)1+-2#) 0)/2*)"- 9/&7

    8-(0*+07-,80)1+-2#):;3

    >

    !'()*#+0"0*#8-(0*+07-,80)1+-2#) %&0./+0"/#&:;4

    -&0'-/80)1+-2#)M-+=-(%0)/2*)"-3

    >

    >

    The problem with above serialized singleton class is that whenever wedeserialize it, it will create a new instance of the class. Lets see it with a

    simple program.

    !"#$"%&"#$%'()*+,-.%/0)1+-2#)3

    *

    *

    *

    *

    8-(0*+07-,80)1+-2#) 0)/2*)"-P)- 9

    8-(0*+07-,80)1+-2#)%1-26)/2*)"-:;3

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    15/132

    !#$%&'()*+,-.$/ 0(1+ "/$2 "#$

    PA&-"2P'2='2 #'2 9/&7PA&-"2P'2='282(-*$:/&7W0+-P'2='282(-*$:

    EB0+-)*$-%/-(E;;3

    #'2%Q(02-PA&-"2:0)/2*)"-P)-;3

    #'2%"+#/-:;3

  • 8/10/2019 Java Design Pattern eBook

    16/132

    !#$%&'()*+,-.$/ 0(1+ "9$2 "#$

    $; O&C.*5G 4&..)5-

    Factory Pattern is one of the Creational Design patternand its widely

    used in JDK as well as frameworks like Spring and Struts.

    Factory design pattern is used when we have a super class with multiple sub-classes and based on input, we need to return one of the sub-class. This

    pattern take out the responsibility of instantiation of a class from clientprogram to the factory class. Lets first learn how to implement factory

    pattern in java and then we will learn its benefits and we will see its usage inJDK.

    >;

    VR5&--*2&

    !'()*#82(0)1 0430-*/%:;4

    -&0'-/EZK[9 EY0:*+%1-2ZK[:;YEX MRR9EY0:*+%1-2MRR:;YEX

    LIU9EY0:*+%1-2LIU:;3

    >

    >

    B;

  • 8/10/2019 Java Design Pattern eBook

    17/132

    !#$%&'()*+,-.$/ 0(1+ ":$2 "#$

    !"#$"%&"#$%'()*+,-.%,-/01)%$#,-+3

    !'()*##)"++BF&=0&/2+L#$='2-( 4

    !-*5"0&82(0)1 (*$3!-*5"0&82(0)1 D,,3

    !-*5"0&82(0)1 "='3

    !'()*#BF:82(0)1 (*$X82(0)1 D,,X82(0)1 "=';4

    0:*+%(*$9(*$3

    0:*+%D,,9D,,3

    0:*+%"='9"='3

    >

    VR5&--*2&

    !'()*#82(0)1 %&0;TU:;4

    -&0'-/0:*+%(*$3>

    VR5&--*2&

    !'()*#82(0)1 %&0CAA:;4

    -&0'-/0:*+%D,,3

    >

    VR5&--*2&

    !'()*#82(0)1 %&0FB@:;4

    -&0'-/0:*+%"='3

    >

    >

    Notice that both the classes are extending Computer class.

    !"#$"%&"#$%'()*+,-.%,-/01)%$#,-+3

    !'()*##)"++3&-5&-&=0&/2+L#$='2-( 4

    !-*5"0&82(0)1 (*$3

    !-*5"0&82(0)1 D,,3

    !-*5"0&82(0)1 "='3

    !'()*#3&-5&-:82(0)1 (*$X82(0)1 D,,X82(0)1 "=';4

    0:*+%(*$9(*$3

    0:*+%D,,9D,,3

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    18/132

    !#$%&'()*+,-.$/ 0(1+ "=$2 "#$

    0:*+%"='9"='3

    >

    VR5&--*2&

    !'()*#82(0)1 %&0;TU:;4

    -&0'-/0:*+%(*$3

    >

    VR5&--*2&

    !'()*#82(0)1 %&0CAA:;4

    -&0'-/0:*+%D,,3

    >

    VR5&--*2&

    !'()*#82(0)1 %&0FB@:;4

    -&0'-/0:*+%"='3

    >

    >

    ,; O&C.*5G ,(&11

    Now that we have super classes and sub-classes ready, we can write ourfactory class. Here is the basic implementation.

    !"#$"%&"#$%'()*+,-.%,-/01)%B*"2#(G3

    *

    *

  • 8/10/2019 Java Design Pattern eBook

    19/132

    !#$%&'()*+,-.$/ 0(1+ "E$2 "#$

    1. We can keep Factory class Singletonor we can keep the method thatreturns the subclass asstatic.

    2.Notice that based on the input parameter, different subclass is createdand returned.

    Here is a simple test client program that uses above factory patternimplementation.

    !"#$"%&"#$%'()*+,-.%,-/01)%2-/23

    *

    *

    !'()*##)"++?&+0P"#04-94

    !'()*#+0"0*#54*2

  • 8/10/2019 Java Design Pattern eBook

    20/132

    !#$%&'()*+,-.$/ 0(1+ "H$2 "#$

    >

    Output of above program is:

    W*"2#(G IL F4/6*%WSZK[9M^?XMRR9OII^?XLIU9MEJ^M7

    W*"2#(G 8-(.-( F4/6*%WSZK[9NH^?XMRR9NH?XLIU9MEK^M7

    0; B)-)+2.1 *+ O&C.*5G 4&..)5-

    1. Factory pattern provides approach to code for interface rather thanimplementation.

    2. Factory pattern removes the instantiation of actual implementationclasses from client code, making it more robust, less coupled and easyto extend. For example, we can easily change PC class

    implementation because client program is unaware of this.3. Factory pattern provides abstraction between implementation and

    client classes through inheritance.

    ?; O&C.*5G 4&..)5- ?T&MN()1 2- U0V

    1.java.util.Calendar, ResourceBundle and NumberFormat getInstance()methods uses Factory pattern.

    2. valueOf() method in wrapper classes like Boolean, Integer etc.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    21/132

    !#$%&'()*+,-.$/ 0(1+ $K$2 "#$

    #; >'1.5&C. O&C.*5G 4&..)5-

    Abstract Factory is one of the Creational pattern and almost similar toFactory Patternexcept the fact that itsmore like factory of factories.

    If you are familiar withfactory design pattern in java,you will notice thatwe have a single Factory class that returns the different sub-classes based onthe input provided and factory class uses if-else or switch statement toachieve this.

    In Abstract Factory pattern, we get rid of if-else block and have a factoryclass for each sub-class and then an Abstract Factory class that will returnthe sub-class based on the input factory class. At first it seems confusing but

    once you see the implementation, its really easy to grasp and understand theminor difference between Factory and Abstract Factory pattern.

    Like our factory pattern post, we will use the same super class and sub-classes.

    >;

    !'()*#"(+0-"#082(0)1 %&0;TU:;3

    !'()*#"(+0-"#082(0)1 %&0CAA:;3

    !'()*#"(+0-"#082(0)1 %&0FB@:;3

    VR5&--*2&

    !'()*#82(0)1 0430-*/%:;4

    -&0'-/EZK[9 EY0:*+%1-2ZK[:;YEX MRR9EY0:*+%1-2MRR:;YEX

    LIU9EY0:*+%1-2LIU:;3

    >>

    !"#$"%&"#$%'()*+,-.%,-/01)%$#,-+3

    !'()*##)"++BF&=0&/2+L#$='2-( 4

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1392/factory-design-pattern-in-javahttp://www.journaldev.com/1392/factory-design-pattern-in-javahttp://www.journaldev.com/1392/factory-design-pattern-in-javahttp://www.journaldev.com/1392/factory-design-pattern-in-javahttp://www.journaldev.com/1392/factory-design-pattern-in-javahttp://www.journaldev.com/1392/factory-design-pattern-in-javahttp://www.journaldev.com/1392/factory-design-pattern-in-javahttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    22/132

    !#$%&'()*+,-.$/ 0(1+ $"$2 "#$

    !-*5"0&82(0)1 (*$3

    !-*5"0&82(0)1 D,,3

    !-*5"0&82(0)1 "='3

    !'()*#BF:82(0)1 (*$X82(0)1 D,,X82(0)1 "=';40:*+%(*$9(*$3

    0:*+%D,,9D,,3

    0:*+%"='9"='3

    >

    VR5&--*2&

    !'()*#82(0)1 %&0;TU:;4

    -&0'-/0:*+%(*$3

    >

    VR5&--*2&

    !'()*#82(0)1 %&0CAA:;4-&0'-/0:*+%D,,3

    >

    VR5&--*2&

    !'()*#82(0)1 %&0FB@:;4

    -&0'-/0:*+%"='3

    >

    >

    !"#$"%&"#$%'()*+,-.%,-/01)%$#,-+3

    !'()*##)"++3&-5&-&=0&/2+L#$='2-( 4

    !-*5"0&82(0)1 (*$3

    !-*5"0&82(0)1 D,,3

    !-*5"0&82(0)1 "='3

    !'()*#3&-5&-:82(0)1 (*$X82(0)1 D,,X82(0)1 "=';4

    0:*+%(*$9(*$30:*+%D,,9D,,3

    0:*+%"='9"='3

    >

    VR5&--*2&

    !'()*#82(0)1 %&0;TU:;4

    -&0'-/0:*+%(*$3

    >

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    23/132

    !#$%&'()*+,-.$/ 0(1+ $$$2 "#$

    VR5&--*2&

    !'()*#82(0)1 %&0CAA:;4

    -&0'-/0:*+%D,,3

    >

    VR5&--*2&

    !'()*#82(0)1 %&0FB@:;4

    -&0'-/0:*+%"='3

    >

    >

    B; O&C.*5G ,(&11)1 +*5 ?&CI 1L'WC(&11

    First of all we need to create an Abstract Factory interface orabstract class.

    !"#$"%&"#$%'()*+,-.%,-/01)%*A/2(*"2B*"2#(G3

    *

    !'()*#*/0&-6"#&F4

    >

    Notice that createComputer()method is returning an instance of super classComputer. Now our factory classes will implement this interface and returntheir respective sub-class.

    !"#$"%&"#$%'()*+,-.%,-/01)%*A/2(*"2B*"2#(G3

    *

    *

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    24/132

    !#$%&'()*+,-.$/ 0(1+ $#$2 "#$

    !'()*#BFP"#04-9:82(0)1 (*$X82(0)1 D,,X82(0)1 "=';4

    0:*+%(*$9(*$3

    0:*+%D,,9D,,3

    0:*+%"='9"='3

    >VR5&--*2&

    !'()*#L#$='2-( #-&"0&F4

    !'()*##)"++3&-5&-P"#04-9*

    !'()*#3&-5&-P"#04-9:82(0)1 (*$X82(0)1 D,,X82(0)1 "=';4

    0:*+%(*$9(*$3

    0:*+%D,,9D,,3

    0:*+%"='9"='3

    >

    VR5&--*2&

    !'()*#L#$='2-( #-&"0&F4

  • 8/10/2019 Java Design Pattern eBook

    25/132

    !#$%&'()*+,-.$/ 0(1+ $/$2 "#$

    =*"@*1-"#$%'()*+,-.%,-/01)%*A/2(*"2B*"2#(G3

    0$=#(2"#$%'()*+,-.%,-/01)%$#,-+%L#$='2-(3

    ='A+0""+*//L#$='2-(W*"2#(G 4

    ='A+0"/2*20"L#$='2-( 1-2L#$='2-(:L#$='2-(KA/2(*"2W*"2#(G B*"2#(G;4(-2'()B*"2#(G%"(-*2-L#$='2-(:;3

    >>

    Notice that its a simple class and getComputer method is acceptingComputerAbstractFactoryargument and returning Computerobject. At this

    point the implementation must be getting clear.

    Lets write a simple test method and see how to use the abstract factory toget the instance of sub-classes.

    !"#$"%&"#$%'()*+,-.%,-/01)%2-/23

    *

    *

    !'()*##)"++?&+0A&+*%/B"00&-/+4

    !'()*#+0"0*#54*2

  • 8/10/2019 Java Design Pattern eBook

    26/132

    !#$%&'()*+,-.$/ 0(1+ $9$2 "#$

    P'2='2 #B 2D- *A#.- =(#1(*$ Q0++ A-S

    KA/2(*"2W*"2#(G IL L#)B01SSZK[9 ] ^?X MRR9_`` ^?X LIU9]%a ^M7KA/2(*"2W*"2#(G 8-(.-( L#)B01SSZK[9 bc ^?X MRR9b H?X LIU9]%d ^M7

    3454 67 894 :;

  • 8/10/2019 Java Design Pattern eBook

    27/132

    !#$%&'()*+,-.$/ 0(1+ $:$2 "#$

    /; BL2(J)5 4&..)5-

    Builder design pattern is a creational design patternlikeFactory Pattern

    andAbstract Factory Pattern.This pattern was introduced to solve someof the problems with Factory and Abstract Factory design patterns when theObject contains a lot of attributes.

    There are three major issues with Factory and Abstract Factory designpatterns when the Object contains a lot of attributes.

    1. Too Many arguments to pass from client program to the Factory classthat can be error prone because most of the time, the type ofarguments are same and from client side its hard to maintain theorder of the argument.

    2. Some of the parameters might be optional but in Factory pattern, weare forced to send all the parameters and optional parameters need tosend as NULL.

    3. If the object is heavy and its creation is complex, then all thatcomplexity will be part of Factory classes that is confusing.

    We can solve the issues with large number of parameters by providing aconstructor with required parameters and then different setter methods to set

    the optional parameters but the problem with this is that the Object state willbe inconsistentuntil unless all the attributes are set explicitly.

    Builder pattern solves the issue with large number of optional parametersand inconsistent state by providing a way to build the object step-by-stepand provide a method that will actually return the final Object.

    >; BL2(J)5 4&..)5- @MN()M)-.&.2*-

    1.

    First of all you need to create a static nested classand then copy allthe arguments from the outer class to the Builder class. We shouldfollow the naming convention and if the class name is Computerthen

    builder class should be named as ComputerBuilder.2. The Builder class should have a public constructor with all the

    required attributes as parameters.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1392/factory-design-pattern-in-javahttp://www.journaldev.com/1392/factory-design-pattern-in-javahttp://www.journaldev.com/1392/factory-design-pattern-in-javahttp://www.journaldev.com/1418/abstract-factory-design-pattern-in-javahttp://www.journaldev.com/1418/abstract-factory-design-pattern-in-javahttp://www.journaldev.com/1418/abstract-factory-design-pattern-in-javahttp://www.journaldev.com/996/java-nested-classes-java-inner-class-static-nested-class-local-inner-class-and-anonymous-inner-classhttp://www.journaldev.com/996/java-nested-classes-java-inner-class-static-nested-class-local-inner-class-and-anonymous-inner-classhttp://www.journaldev.com/996/java-nested-classes-java-inner-class-static-nested-class-local-inner-class-and-anonymous-inner-classhttp://www.journaldev.com/1418/abstract-factory-design-pattern-in-javahttp://www.journaldev.com/1392/factory-design-pattern-in-javahttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    28/132

    !#$%&'()*+,-.$/ 0(1+ $=$2 "#$

    3. Builder class should have methods to set the optional parameters andit should return the same Builder object after setting the optionalattribute.

    4. The final step is to provide a build() method in the builder class thatwill return the Object needed by client program. For this we need tohave a private constructor in the Class with Builder class as argument.

    Here is the sample code where we have a Computer class andComputerBuilder class to build it.

    D

    !'()*#82(0)1 %&0;TU:;4

    -&0'-/ZK[3

    >

    !'()*#(44)&"/*+X-"!:*#+F"-2,/"()&2:;4

    -&0'-/0/^(*=D0"/L*(,5)*A+-,3

    >

    !'()*#(44)&"/*+8)'&0440:,/"()&2:;4

    -&0'-/0/?+'-2##2D5)*A+-,3

    >

    !-*5"0&F4

    0:*+%MRR9A'0+,-(%MRR3

    0:*+%ZK[9A'0+,-(%ZK[3

    0:*+%0/^(*=D0"/L*(,5)*A+-,9A'0+,-(%0/^(*=D0"/L*(,5)*A+-,3

    0:*+%0/?+'-2##2D5)*A+-,9A'0+,-(%0/?+'-2##2D5)*A+-,3

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    29/132

    !#$%&'()*+,-.$/ 0(1+ $E$2 "#$

    >

  • 8/10/2019 Java Design Pattern eBook

    30/132

    !#$%&'()*+,-.$/ 0(1+ $H$2 "#$

    *

    !'()*#+0"0*#54*2

  • 8/10/2019 Java Design Pattern eBook

    31/132

    !#$%&'()*+,-.$/ 0(1+ #K$2 "#$

    9; 45*.*.GN) 4&..)5-

    Prototype patternis one of the Creational Design pattern, so it provides a

    mechanism of object creation. Prototype pattern is used when the Objectcreation is a costly affair and requires a lot of time and resources and youhave a similar object already existing. So this pattern provides a mechanismto copy the original object to a new object and then modify it according toour needs. This pattern uses java cloning to copy the object.

    It would be easy to understand this pattern with an example, suppose wehave an Object that loads data from database. Now we need to modify thisdata in our program multiple times, so its not a good idea to create the

    Object using newkeyword and load all the data again from database. So thebetter approach is to clone the existing object into a new object and then dothe data manipulation.

    Prototype design pattern mandates that the Object which you are copyingshould provide the copying feature. It should not be done by any other class.However whether to use shallow or deep copy of the Object propertiesdepends on the requirements and its a design decision.

    Here is a sample program showing implementation of Prototype pattern.

    !"#$"%&"#$%'()*+,-.%,-/01)%=(#2#2G=-3

    **+03

    !'()*##)"++,

    !-*5"0&F0/2e82(0)1f-$=F0/23

    !'()*#,

    -$=F0/2 9/&7K((*GF0/2e82(0)1f:;3>

    !'()*#,

    0:*+%-$=F0/29+0/23

    >

    !'()*#54*2)4"2A"0":;4

  • 8/10/2019 Java Design Pattern eBook

    32/132

    !#$%&'()*+,-.$/ 0(1+ #"$2 "#$

    -$=F0/2%*,,:EI*)@*&E;3

    -$=F0/2%*,,:EZ*&E;3

    -$=F0/2%*,,:ER*.0,E;3

    -$=F0/2%*,,:EF0/*E;3

    >

    !'()*#F0/2e82(0)1f%&0,*+0:;4

    -&0'-/-$=F0/23

    >

    VR5&--*2&

    !'()*#PA&-"2 #)4/&:;0:-47+L+#)-J#28'==#(2-,5C"-=20#)4

    F0/2e82(0)1f2-$= 9/&7K((*GF0/2e82(0)1f:;3

    64-:82(0)1 / S0:*+%1-25$=F0/2:;;4

    2-$=%*,,:/;3

    >

    -&0'-//&7,

    >

    Notice that the clone method is overridden to provide a deep copy of theemployees list.

    Here is the test program that will show the benefit of prototype patternusage.

    !"#$"%&"#$%'()*+,-.%,-/01)%2-/23

    *

    5$=+#G--/ -$=/ 9/&75$=+#G--/:;3-$=/%+#*,R*2*:;3

  • 8/10/2019 Java Design Pattern eBook

    33/132

    !#$%&'()*+,-.$/ 0(1+ #$$2 "#$

    F0/2e82(0)1f+0/2b 9-$=/J-Qb%1-25$=F0/2:;3

    +0/2b%(-$#.-:EI*)@*&E;3

    8G/2-$%#'2%=(0)2+):E-$=/ F0/2S EY-$=/%1-25$=F0/2:;;3

    8G/2-$%#'2%=(0)2+):E-$=/J-Q F0/2S EY+0/2;3

    8G/2-$%#'2%=(0)2+):E-$=/J-Qb F0/2S EY+0/2b;3>

    >

    $H8DH8 @A 894 5

  • 8/10/2019 Java Design Pattern eBook

    34/132

    !#$%&'()*+,-.$/ 0(1+ ##$2 "#$

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1827/java-design-patterns-example-tutorial#structural-patternshttp://www.journaldev.com/1827/java-design-patterns-example-tutorial#structural-patternshttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    35/132

    !#$%&'()*+,-.$/ 0(1+ #/$2 "#$

    >

    !"#$"%&"#$%'()*+,-.%,-/01)%*,*=2-(3

    !'()*##)"++34#$&04

    !'()*#T#+2 %&0Y4)0:;4

    -&0'-//&7Y4)0:NMI;3

    >

    >

    Now we want to build an adapter that can produce 3 volts, 12 volts anddefault 120 volts. So first of all we will create an adapter interface with thesemethods.

    !"#$"%&"#$%'()*+,-.%,-/01)%*,*=2-(3

    !'()*#*/0&-6"#&34#$&0T2"!0&-4

    !'()*#T#+2 %&0NMIY4)0:;3

    !'()*#T#+2 %&0NMY4)0:;3

    !'()*#T#+2 %&0LY4)0:;3

    >

    >; %8* X&G >J&N.)5 4&..)5-

    While implementing Adapter pattern, there are two approaches classadapter and object adapter, however both these approaches produce sameresult.

    1. Class Adapter This form uses java inheritance and extends thesource interface, in our case Socket class.

    2. Object Adapter This form uses Java Composition and adapter

    contains the source object.

    B; ,(&11 >J&N.)5 @MN()M)-.&.2*-

    Here is the class adapterapproach implementation of our adapter.

    !"#$"%&"#$%'()*+,-.%,-/01)%*,*=2-(3

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/644/inheritance-in-java-examplehttp://www.journaldev.com/644/inheritance-in-java-examplehttp://www.journaldev.com/1325/what-is-composition-in-java-java-composition-examplehttp://www.journaldev.com/1325/what-is-composition-in-java-java-composition-examplehttp://www.journaldev.com/1325/what-is-composition-in-java-java-composition-examplehttp://www.journaldev.com/644/inheritance-in-java-examplehttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    36/132

    !#$%&'()*+,-.$/ 0(1+ #9$2 "#$

    VR5&--*2&!'()*#T#+2 %&0NMIY4)0:;4

    -&0'-/%&0Y4)0:;3

    >

    VR5&--*2&

    !'()*#T#+2 %&0NMY4)0:;4

    T#+2 .91-2T#+2:;3

    -&0'-/#4/5&-0Y4)0:.XNI;3

    >

    VR5&--*2&!'()*#T#+2 %&0LY4)0:;4

    T#+2 .91-2T#+2:;3

    -&0'-/#4/5&-0Y4)0:.XJI;3

    >

    !-*5"0&T#+2 #4/5&-0Y4)0:T#+2 .X*/00;4

    -&0'-//&7Y4)0:.%1-2T#+2/:;

    >

    ,; 6'Y)C. >J&N.)5 @MN()M)-.&.2*-

    Here is the Object adapterimplementation of our adapter.

    !"#$"%&"#$%'()*+,-.%,-/01)%*,*=2-(3

    !'()*##)"++34#$&0R(DT2"!0&-.

    >

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    37/132

    !#$%&'()*+,-.$/ 0(1+ #:$2 "#$

    VR5&--*2&

    !'()*#T#+2 %&0NMY4)0:;4

    T#+2 .9/#"@%1-2T#+2:;3

    -&0'-/#4/5&-0Y4)0:.XNI;3

    >

    VR5&--*2&

    !'()*#T#+2 %&0LY4)0:;4

    T#+2 .9/#"@%1-2T#+2:;3

    -&0'-/#4/5&-0Y4)0:.XJI;3

    >

    !-*5"0&T#+2 #4/5&-0Y4)0:T#+2 .X*/00;4

    -&0'-//&7Y4)0:.%1-2T#+2/:;

    >

    Notice that both the adapter implementations are almost same and theyimplement the SocketAdapterinterface. The adapter interface can also be anabstract class.

    Here is a test program to consume our adapter implementation.

    !"#$"%&"#$%'()*+,-.%,-/01)%2-/23

    *

    !'()*##)"++T2"!0&-B"00&-/?&+04

    !'()*#+0"0*#54*2

    !-*5"0&+0"0*#54*20&+0R(DT2"!0&-:;4

    8#"@-2K,*=2-( /#"@K,*=2-( 9/&78#"@-2PA&-"2K,*=2-(6$=+:;3

    T#+2 .h 91-2T#+2:/#"@K,*=2-(XL;3

    T#+2 .b] 91-2T#+2:/#"@K,*=2-(XNM;3

    T#+2 .b]` 91-2T#+2:/#"@K,*=2-(XNMI;3

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    38/132

    !#$%&'()*+,-.$/ 0(1+ #=$2 "#$

    8G/2-$%#'2%=(0)2+):E.h .#+2/ '/0)1 PA&-"2

    K,*=2-(9EY.h%1-2T#+2/:;;3

    8G/2-$%#'2%=(0)2+):E.b] .#+2/ '/0)1 PA&-"2

    K,*=2-(9EY.b]%1-2T#+2/:;;3

    8G/2-$%#'2%=(0)2+):E.b]` .#+2/ '/0)1 PA&-"2

    K,*=2-(9EY.b]`%1-2T#+2/:;;3>

    !-*5"0&+0"0*#54*20&+0F)"++T2"!0&-:;4

    8#"@-2K,*=2-( /#"@K,*=2-( 9/&78#"@-2L+*//K,*=2-(6$=+:;3

    T#+2 .h 91-2T#+2:/#"@K,*=2-(XL;3

    T#+2 .b] 91-2T#+2:/#"@K,*=2-(XNM;3

    T#+2 .b]` 91-2T#+2:/#"@K,*=2-(XNMI;3

    8G/2-$%#'2%=(0)2+):E.h .#+2/ '/0)1 L+*//

    K,*=2-(9EY.h%1-2T#+2/:;;3

    8G/2-$%#'2%=(0)2+):E.b] .#+2/ '/0)1 L+*//

    K,*=2-(9EY.b]%1-2T#+2/:;;38G/2-$%#'2%=(0)2+):E.b]` .#+2/ '/0)1 L+*//

    K,*=2-(9EY.b]`%1-2T#+2/:;;3

    >

    !-*5"0&+0"0*#T#+2 %&0Y4)0:8#"@-2K,*=2-( /#"@K,*=2-(X*/00;4

    +7*0#::0;4

    #"+&LS-&0'-//#"@K,*=2-(%1-2hT#+2:;3

    #"+&NMS-&0'-//#"@K,*=2-(%1-2b]T#+2:;3

    #"+&NMIS-&0'-//#"@K,*=2-(%1-2b]`T#+2:;3

    2&6"')0S-&0'-//#"@K,*=2-(%1-2b]`T#+2:;3

    >>

    >

    When we run above test program, we get following output.

    .h .#+2/ '/0)1 L+*// K,*=2-(9L

    .b] .#+2/ '/0)1 L+*// K,*=2-(9NM

    .b]` .#+2/ '/0)1 L+*// K,*=2-(9NMI

    .h .#+2/ '/0)1 PA&-"2 K,*=2-(9L

    .b] .#+2/ '/0)1 PA&-"2 K,*=2-(9NM

    .b]` .#+2/ '/0)1 PA&-"2 K,*=2-(9NMI

    0; >J&N.)5 4&..)5- ,(&11 02&35&M

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    39/132

    !#$%&'()*+,-.$/ 0(1+ #E$2 "#$

    ?; >J&N.)5 4&..)5- ?T&MN() 2- U0V

    java.util.Arrays#asList() java.io.InputStreamReader(InputStream) (returns a Reader) java.io.OutputStreamWriter(OutputStream) (returns a Writer)

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    40/132

    !#$%&'()*+,-.$/ 0(1+ #H$2 "#$

    $; ,*MN*12.) 4&..)5-

    Composite pattern is one of the Structural design pattern and is used

    when we have to represent a part-whole hierarchy. When we need to create astructure in a way that the objects in the structure has to be treated the sameway, we can apply composite design pattern.

    Letsunderstand it with a real life example A diagram is a structure thatconsists of Objects such as Circle, Lines, Triangle etc and when we fill thedrawing with color (say Red), the same color also gets applied to the Objectsin the drawing. Here drawing is made up of different parts and they all havesame operations.

    Composite Pattern consists of following objects.

    1. Base ComponentBase component is the interface for all objects inthe composition, client program uses base component to work withthe objects in the composition. It can be an interface or an abstractclasswith some methods common to all the objects.

    2. LeafDefines the behaviour for the elements in the composition. It isthe building block for the composition and implements basecomponent. It doesnt have references to other Components.

    3.

    Composite It consists of leaf elements and implements theoperations in base component.

    Here I am applying composite design pattern for the drawing scenario.

    >; B&1) ,*MN*-)-.

    Base component defines the common methods for leaf and composites, wecan create a class Shapewith a method draw(String fillColor) to draw the

    shape with given color.!"#$"%&"#$%'()*+,-.%,-/01)%"#$=#/02-3

    !'()*#*/0&-6"#&3:"!&4

    !'()*#54*22-"7:82(0)1 B0++L#+#(;3

    >

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    41/132

    !#$%&'()*+,-.$/ 0(1+ /K$2 "#$

    B; F)&+ 6'Y)C.1

    Leaf implements base component and these are the building block for thecomposite. We can create multiple leaf objects such as Triangle, Circle etc.

    !"#$"%&"#$%'()*+,-.%,-/01)%"#$=#/02-3

    !'()*##)"++?-*"/%)&*

    VR5&--*2&

    !'()*#54*22-"7:82(0)1 B0++L#+#(;4

    8G/2-$%#'2%=(0)2+):ER(*Q0)1 H(0*)1+- Q02D "#+#( EYB0++L#+#(;3

    >

    >

    !"#$"%&"#$%'()*+,-.%,-/01)%"#$=#/02-3

    !'()*##)"++F*-#)&*

    VR5&--*2&

    !'()*#54*22-"7:82(0)1 B0++L#+#(;4

    8G/2-$%#'2%=(0)2+):ER(*Q0)1 L0("+- Q02D "#+#( EYB0++L#+#(;3

    >

    >

    ,; ,*MN*12.)

    A composite object contains group of leaf objects and we should providesome helper methods to add or delete leafs from the group. We can also

    provide a method to remove all the elements from the group.!"#$"%&"#$%'()*+,-.%,-/01)%"#$=#/02-3

    **+03

    !'()*##)"++A-"7*/%*

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    42/132

    !#$%&'()*+,-.$/ 0(1+ /"$2 "#$

    >

  • 8/10/2019 Java Design Pattern eBook

    43/132

    !#$%&'()*+,-.$/ 0(1+ /$$2 "#$

    Our composite pattern implementation is ready and we can test it with a

    client program.!"#$"%&"#$%'()*+,-.%,-/01)%2-/23

    *

    *

    !'()*##)"++?&+0F4

  • 8/10/2019 Java Design Pattern eBook

    44/132

    !#$%&'()*+,-.$/ 0(1+ /#$2 "#$

    ,(*Q0)1%*,,:"0(;3

    ,(*Q0)1%,(*Q:EZ-,E;3

    ,(*Q0)1%"+-*(:;3

    ,(*Q0)1%*,,:2(0;3

    ,(*Q0)1%*,,:"0(;3

    ,(*Q0)1%,(*Q:E^(--)E;3

    >

    >

    Output of the above program is:

    R(*Q0)1 H(0*)1+- Q02D "#+#( Z-,

    R(*Q0)1 H(0*)1+- Q02D "#+#( Z-,

    R(*Q0)1 L0("+- Q02D "#+#( Z-,

    L+-*(0)1 *++ 2D- /D*=-/ B(#$ ,(*Q0)1

    R(*Q0)1 H(0*)1+- Q02D "#+#( ^(--)

    R(*Q0)1 L0("+- Q02D "#+#( ^(--)

    0; @MN*5.&-. 4*2-.1 &'*L. ,*MN*12.) 4&..)5-

    Composite pattern should be applied only when the group of objectsshould behave as the single object.

    Composite pattern can be used to create a tree like structure.

    java.awt.Container#add(Component) is a great example of Compositepattern in java and used a lot in Swing.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    45/132

    !#$%&'()*+,-.$/ 0(1+ //$2 "#$

    #; 45*TG 4&..)5-

    Proxy Design patternis one of the Structural design patternand in my

    opinion one of the simplest pattern to understand. Proxy pattern intentaccording to GoF is:

    The definition itself is very clear and proxy pattern is used when we want to

    provide controlled access of a functionality. Lets say we have a class thatcan run some command on the system. Now if we are using it, its fine but ifwe want to give this program to a client application, it can have severe issues

    because client program can issue command to delete some system files orchange some settings that you dont want. Here a proxy class can be createdto provide controlled access of the program.

    >; Z&2- ,(&11

    Since we code Java in terms of interfaces, here is our interface and itsimplementation class.

    !"#$"%&"#$%'()*+,-.%,-/01)%=(#CG3

    !'()*#*/0&-6"#&F4

    !"#$"%&"#$%'()*+,-.%,-/01)%=(#CG3

    *

    !'()*##)"++F4

  • 8/10/2019 Java Design Pattern eBook

    46/132

    !#$%&'()*+,-.$/ 0(1+ /9$2 "#$

    B; 45*TG ,(&11

    Now we want to provide only admin users to have full access of above class,if the user is not admin then only limited commands will be allowed. Here isour very simple proxy class implementation.

    !"#$"%&"#$%'()*+,-.%,-/01)%=(#CG3

    !'()*##)"++F4

    *6:EI*)@*&E%-\'*+/:'/-(;jjEgk'()*+Rl.E%-\'*+/:=Q,;;

    0/K,$0)90-'&3

    -C-"'2#( 9/&7L#$$*),5C-"'2#(6$=+:;3

    >

    VR5&--*2&

    !'()*#54*2-'/F4

  • 8/10/2019 Java Design Pattern eBook

    47/132

    !#$%&'()*+,-.$/ 0(1+ /:$2 "#$

    ,; 45*TG 4&..)5- ,(2)-. %)1. 45*35&M

    !"#$"%&"#$%'()*+,-.%,-/01)%2-/23

    *

    *

    !'()*##)"++B-4=9B"00&-/?&+04

    !'()*#+0"0*#54*2#"0#::5C"-=20#) -;4

    8G/2-$%#'2%=(0)2+):E5C"-=20#) [-//*1-SSEY-%1-2[-//*1-:;;3

    >

    >

    >

    Output of above test program is:

    i+/ V+2(i"#$$*), -C-"'2-,%

    5C"-=20#)U&++"%&WS($ "#$$*), 0/ )#2 *++#Q-, 64-)#)V*,$0) '/-(/%

    Proxy pattern common uses are to control access or to provide a wrapperimplementation for better performance.

    Java RMI whole package uses proxy pattern.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    48/132

    !#$%&'()*+,-.$/ 0(1+ /=$2 "#$

    /; O(G8)23I. 4&..)5-

    According to GoF, flyweight design patternintent is:

    Flyweight design pattern is a Structural design patternlikeFacade pattern,Adapter Pattern and Decorator pattern. Flyweight design pattern is usedwhen we need to create a lot of Objects of a class. Since every object

    consumes memory space that can be crucial for low memory devices, suchas mobile devices or embedded systems, flyweight design pattern can beapplied to reduce the load on memory by sharing objects.

    Before we apply flyweight design pattern, we need to consider followingfactors:

    The number of Objects to be created by application should be huge. The object creation is heavy on memory and it can be time consuming

    too. The object properties can be divided into intrinsic and extrinsic

    properties, extrinsic properties of an Object should be defined by theclient program.

    To apply flyweight pattern, we need to divide Object property into intrinsicand extrinsic properties. Intrinsic properties make the Object uniquewhereas extrinsic properties are set by client code and used to performdifferent operations. For example, an Object Circle can have extrinsic

    properties such as color and width.

    For applying flyweight pattern, we need to create a Flyweight factorythatreturns the shared objects. For our example, lets say we need to create a

    drawing with lines and Ovals. So we will have an interface Shape and itsconcrete implementations as Line and Oval. Oval class will have intrinsic

    property to determine whether to fill the Oval with given color or notwhereas Line will not have any intrinsic property.

    Use sharing to support large numbers of fine-grainedobjects efficiently

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1557/facade-pattern-in-java-example-tutorialhttp://www.journaldev.com/1557/facade-pattern-in-java-example-tutorialhttp://www.journaldev.com/1557/facade-pattern-in-java-example-tutorialhttp://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1540/decorator-pattern-in-java-example-tutorialhttp://www.journaldev.com/1540/decorator-pattern-in-java-example-tutorialhttp://www.journaldev.com/1540/decorator-pattern-in-java-example-tutorialhttp://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1557/facade-pattern-in-java-example-tutorialhttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    49/132

    !#$%&'()*+,-.$/ 0(1+ /E$2 "#$

    >; O(G8)23I. @-.)5+&C) &-J ,*-C5).) ,(&11)1

    !"#$"%&"#$%'()*+,-.%,-/01)%B+GQ-01D23

    *

    >

    D98J

    **/&*

    !'()*#>*/&:;4

    8G/2-$%#'2%=(0)2+):EL(-*20)1 F0)- #A&-"2E;3

    >

    VR5&--*2&

    !'()*#54*22-"7:^(*=D0"/ +0)-X*/0CbX*/0GbX*/0C]X*/0G]X

    L#+#( "#+#(;4

    +0)-%/-2L#+#(:"#+#(;3

    +0)-%,(*QF0)-:CbXGbXC]XG];3

    >

    >

    !"#$"%&"#$%'()*+,-.%,-/01)%B+GQ-01D23

    *

  • 8/10/2019 Java Design Pattern eBook

    50/132

    !#$%&'()*+,-.$/ 0(1+ /H$2 "#$

    VR5&--*2&

    !'()*#54*22-"7:^(*=D0"/ "0("+-X*/0CX*/0GX*/0Q0,2DX*/0

    D-01D2X

    L#+#( "#+#(;4"0("+-%/-2L#+#(:"#+#(;3

    "0("+-%,(*QP.*+:CXGXQ0,2DXD-01D2;3

    *6:B0++;4

    "0("+-%B0++P.*+:CXGXQ0,2DXD-01D2;3

    >

    >

    >

    Notice that I have intentionally introduced delay in creating the Object ofconcrete classes to make the point that flyweight pattern can be used forObjects that takes a lot of time while instantiated.

    B; O(G8)23I. O&C.*5G

    The flyweight factory will be used by client programs to instantiate theObject, so we need to keep a map of Objects in the factory that should not beaccessible by client application. Whenever client program makes a call to

    get an instance of Object, it should be returned from the HashMap, if notfound then create a new Object and put in the Map and then return it. Weneed to make sure that all the intrinsic properties are considered whilecreating the Object.

    Our flyweight factory class looks like below code.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    51/132

    !#$%&'()*+,-.$/ 0(1+ 9K$2 "#$

    !"#$"%&"#$%'()*+,-.%,-/01)%B+GQ-01D23

    *

    M*/D[*=e8D*=-HG=-X8D*=-f:;3

    !'()*#+0"0*#8D*=- %&03:"!&:8D*=-HG=- 2G=-;4

    8D*=- /D*=-6$=+ 9/D*=-/%1-2:2G=-;3

    *6:/D*=-6$=+ 99/'));4

    *6:2G=-%-\'*+/:8D*=-HG=-%PTKFnW6FF;;4

    /D*=-6$=+ 9/&7P.*+:0-'&;3>&)+&*6:2G=-%-\'*+/:8D*=-HG=-%PTKFnJPW6FF;;4

    /D*=-6$=+ 9/&7P.*+:6")+&;3

    >&)+&*6:2G=-%-\'*+/:8D*=-HG=-%F6J5;;4

    /D*=-6$=+ 9/&7F0)-:;3

    >

    /D*=-/%='2:2G=-X/D*=-6$=+;3

    >

    -&0'-//D*=-6$=+3

    >

    !'()*#+0"0*#&/'

    >

    Notice the use ofJava Enumfor type safety,Java Composition(shapes map)andFactory patternin getShapemethod.

    ,; O(G8)23I. 4&..)5- ,(2)-. ?T&MN()

    Below is a sample program that consumes flyweight pattern implementation.

    !"#$"%&"#$%'()*+,-.%,-/01)%B+GQ-01D23

    *

  • 8/10/2019 Java Design Pattern eBook

    52/132

    !#$%&'()*+,-.$/ 0(1+ 9"$2 "#$

    *

    *

    **+0&/&-3

    *

    !'()*##)"++A-"7*/%F)*&/0&=0&/2+gW(*$-4

    !-*5"0&+0"0*#6*/"))4/%/-(0*+T-(/0#)U6R 9VNLOIMIIJLGMSOMSMOOI>3

    !-*5"0&6*/")*/0m6RHM3

    !-*5"0&6*/")*/0M56^MH3

    !-*5"0&+0"0*#6*/")8D*=-HG=- /D*=-/NO948D*=-HG=-%F6J5X

    8D*=-HG=-%PTKFnW6FFX8D*=-HG=-%PTKFnJPW6FF>3

    !-*5"0&+0"0*#6*/")L#+#( "#+#(/NO94L#+#(%Z5RXL#+#(%^Z55JX

    L#+#(%o5FFPm>3

    !'()*#A-"7*/%F)*&/0:*/0Q0,2DX*/0D-01D2;4

    0:*+%m6RHM9Q0,2D3

    0:*+%M56^MH9D-01D23

    L#)2*0)-( "#)2-)2I*)- 91-2L#)2-)2I*)-:;3

    g?'22#) /2*(2?'22#) 9/&7g?'22#):ER(*QE;36*/")gI*)-+ =*)-+ 9/&7gI*)-+:;3

    "#)2-)2I*)-%*,,:=*)-+X?#(,-(F*G#'2%L5JH5Z;3

    "#)2-)2I*)-%*,,:/2*(2?'22#)X?#(,-(F*G#'2%8PUHM;3

    /-2807-:m6RHMXM56^MH;3

    /-2R-B*'+2L+#/-P=-(*20#):gW(*$-%5p6HnPJnLFP85;3

    /-2T0/0A+-:0-'&;3

    /2*(2?'22#)%*,,K"20#)F0/2-)-(:/&7K"20#)F0/2-)-(:;4

    !'()*#54*2"#0*4/B&-64-

  • 8/10/2019 Java Design Pattern eBook

    53/132

    !#$%&'()*+,-.$/ 0(1+ 9$$2 "#$

    >

    >

    >;3

    >

    !-*5"0&8D*=-HG=- %&0;"/24

  • 8/10/2019 Java Design Pattern eBook

    54/132

    !#$%&'()*+,-.$/ 0(1+ 9#$2 "#$

    And you will see following output in command line confirming that Objectsare shared.

    L(-*20)1 F0)- #A&-"2

    L(-*20)1 P.*+ #A&-"2 Q02D B0++90-'&

    L(-*20)1 P.*+ #A&-"2 Q02D B0++96")+&

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    55/132

    !#$%&'()*+,-.$/ 0(1+ 9/$2 "#$

    Thats all for flyweight pattern, we will look into more design patterns infuture posts. If you liked it, please share your thoughts in comments sectionand share it with others too.

    0; O(G8)23I. 4&..)5- ?T&MN() 2- U0V

    All the wrapper classesvalueOf() method uses cached objects showing useof Flyweight design pattern. The best example is Java String class StringPoolimplementation.

    ?; @MN*5.&-. 4*2-.1

    In our example, the client code is not forced to create object usingFlyweight factory but we can force that to make sure client code usesflyweight pattern implementation but its a complete design decisionfor particular application.

    Flyweight pattern introduces complexity and if number of sharedobjects are huge then there is a trade of between memory and time, sowe need to use it judiciously based on our requirements.

    Flyweight pattern implementation is not useful when the number ofintrinsic properties of Object is huge, making implementation of

    Factory class complex.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1002/java-wrapper-classes-tutorial-with-exampleshttp://www.journaldev.com/1002/java-wrapper-classes-tutorial-with-exampleshttp://www.journaldev.com/1321/java-string-interview-questions-and-answershttp://www.journaldev.com/1321/java-string-interview-questions-and-answershttp://www.journaldev.com/797/what-is-java-string-poolhttp://www.journaldev.com/797/what-is-java-string-poolhttp://www.journaldev.com/797/what-is-java-string-poolhttp://www.journaldev.com/797/what-is-java-string-poolhttp://www.journaldev.com/797/what-is-java-string-poolhttp://www.journaldev.com/1321/java-string-interview-questions-and-answershttp://www.journaldev.com/1002/java-wrapper-classes-tutorial-with-exampleshttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    56/132

    !#$%&'()*+,-.$/ 0(1+ 99$2 "#$

    9; O&C&J) 4&..)5-

    Facade Patternis one of the Structural design patterns(such asAdapterpatternandDecorator pattern) and used to help client applications to easilyinteract with the system.

    According to GoF Facade design pattern is:

    Provide a unified interface to a set of interfaces in a subsystem. FacadePattern defines a higher-level interface that makes the subsystem easier touse.

    Suppose we have an application with set of interfaces to use MySql/Oracledatabase and to generate different types of reports, such as HTML report,PDF report etc. So we will have different set of interfaces to work withdifferent types of database. Now a client application can use these interfaces

    to get the required database connection and generate reports. But when thecomplexity increases or the interface behavior names are confusing, clientapplication will find it difficult to manage it. So we can apply Facade patternhere and provide awrapperinterface on top of the existing interface to helpclient application.

    >; !'()*##)"++U93^)C&)!&-4

    Provide a unified interface to a set of interfaces in a

    subsystem. Facade Pattern defines a higher-levelinterface that makes the subsystem easier to use

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1540/decorator-pattern-in-java-example-tutorialhttp://www.journaldev.com/1540/decorator-pattern-in-java-example-tutorialhttp://www.journaldev.com/1002/java-wrapper-classes-tutorial-with-exampleshttp://www.journaldev.com/1002/java-wrapper-classes-tutorial-with-exampleshttp://www.journaldev.com/1002/java-wrapper-classes-tutorial-with-exampleshttp://www.journaldev.com/1002/java-wrapper-classes-tutorial-with-exampleshttp://www.journaldev.com/1540/decorator-pattern-in-java-example-tutorialhttp://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    57/132

    !#$%&'()*+,-.$/ 0(1+ 9:$2 "#$

    !'()*#+0"0*#L#))-"20#) %&0U93^)A8F4//*4/:;4

    ;&!4-0:82(0)1 2*A+-J*$-XL#))-"20#)

    "#);4

    !"#$"%&"#$%'()*+,-.%,-/01)%B*"*,-3

    *

    !'()*##)"++R-"#)&C&)!&-4

    !'()*#+0"0*#L#))-"20#) %&0R-"#)&A8F4//*4/:;4

  • 8/10/2019 Java Design Pattern eBook

    58/132

  • 8/10/2019 Java Design Pattern eBook

    59/132

    !#$%&'()*+,-.$/ 0(1+ 9E$2 "#$

    ,; ,(2)-. 45*35&M

    Now letssee client code without using Facade and using Facade interface.

    !"#$"%&"#$%'()*+,-.%,-/01)%2-/23

    *

    *

    54*2

    >

    As you can see that using Facade interface is a lot easier and cleaner wayand avoid having a lot of logic at client side. JDBC Driver Manager Class toget the database connection is a wonderful example of facade pattern.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    60/132

    !#$%&'()*+,-.$/ 0(1+ 9H$2 "#$

    0; @MN*5.&-. 4*2-.1

    Facade pattern is more like a helper for client applications, it doesnt

    hide subsystem interfaces from the client. Whether to use Facade or

    not is completely dependent on client code. Facade pattern can be applied at any point of development, usually

    when the number of interfaces grow and system gets complex. Subsystem interfaces are not aware of Facade and they shouldnt have

    any reference of the Facade interface. Facade pattern should be applied for similar kind of interfaces, its

    purpose is to provide a single interface rather than multiple interfacesthat does the similar kind of jobs.

    We can use Factory patternwith Facade to provide better interface toclient systems.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1392/factory-design-pattern-in-javahttp://www.journaldev.com/1392/factory-design-pattern-in-javahttp://www.journaldev.com/1392/factory-design-pattern-in-javahttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    61/132

    !#$%&'()*+,-.$/ 0(1+ :K$2 "#$

    :; B52J3) 4&..)5-

    When we have interface hierarchies in both interfaces as well as

    implementations, then builder design pattern is used to decouple theinterfaces from implementation and hiding the implementation details fromthe client programs. Like Adapter pattern,its one of the Structural designpattern.

    According to GoF bridge design pattern is:

    The implementation of bridge design pattern follows the notion to preferCompositionoverinheritance.

    If we look into this design pattern with example, it will be easy tounderstand. Letssay we have an interface hierarchy in both interfaces andimplementations like below image.

    Decouple an abstraction from its implementation sothat the two can vary independently

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1325/what-is-composition-in-java-java-composition-examplehttp://www.journaldev.com/1325/what-is-composition-in-java-java-composition-examplehttp://www.journaldev.com/644/inheritance-in-java-examplehttp://www.journaldev.com/644/inheritance-in-java-examplehttp://www.journaldev.com/644/inheritance-in-java-examplehttp://www.journaldev.com/644/inheritance-in-java-examplehttp://www.journaldev.com/1325/what-is-composition-in-java-java-composition-examplehttp://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    62/132

    !#$%&'()*+,-.$/ 0(1+ :"$2 "#$

    Now we will use bridge design pattern to decouple the interfaces fromimplementation and the UML diagram for the classes and interfaces afterapplying bridge pattern will look like below image.

    Notice the bridge between Shape and Color interfaces and use ofcomposition in implementing the bridge pattern.

    Here is the java code for Shape and Color interfaces.

    !"#$"%&"#$%'()*+,-.%,-/01)%A(0,1-3

    !'()*#*/0&-6"#&F4)4-4

    !'()*#54*2"!!)9F4)4-:;3

    >

    !"#$"%&"#$%'()*+,-.%,-/01)%A(0,1-3

    !'()*#"(+0-"#0#)"++3:"!&4

    "(+0-"#0!'()*#54*2"!!)9F4)4-:;3

    >

    We have Triangle and Pentagon implementation classes as below.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    63/132

    !#$%&'()*+,-.$/ 0(1+ :$$2 "#$

    =*"@*1-"#$%'()*+,-.%,-/01)%A(0,1-3

    !'()*##)"++?-*"/%)&&=0&/2+8D*=-4

    !'()*#?-*"/%)&:L#+#( ";4

    +'!&-:";3

    >

    VR5&--*2&

    !'()*#54*2"!!)9F4)4-:;4

    8G/2-$%#'2%=(0)2:EH(0*)1+- B0++-, Q02D "#+#( E;3

    "#+#(%*==+GL#+#(:;3

    >

    >

    !"#$"%&"#$%'()*+,-.%,-/01)%A(0,1-3

    !'()*##)"++B&/0"%4/&=0&/2+8D*=-4

    !'()*#B&/0"%4/:L#+#( ";4

    +'!&-:";3

    >

    VR5&--*2&

    !'()*#54*2"!!)9F4)4-:;4

    8G/2-$%#'2%=(0)2:EI-)2*1#) B0++-, Q02D "#+#( E;3

    "#+#(%*==+GL#+#(:;3

    >

    >

    Here are the implementation classes for RedColor and GreenColor.

    =*"@*1-"#$%'()*+,-.%,-/01)%A(0,1-3

    ='A+0""+*//Z-,L#+#( 0$=+-$-)2/L#+#(4

    ='A+0".#0,*==+GL#+#(:;48G/2-$%#'2%=(0)2+):E(-,%E;3

    >>

    !"#$"%&"#$%'()*+,-.%,-/01)%A(0,1-3

    !'()*##)"++X-&&/F4)4-*

    !'()*#54*2"!!)9F4)4-:;4

    8G/2-$%#'2%=(0)2+):E1(--)%E;3

    >

    >

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    64/132

    !#$%&'()*+,-.$/ 0(1+ :#$2 "#$

    Letstest our bridge pattern implementation with a test program.

    !"#$"%&"#$%'()*+,-.%,-/01)%2-/23

    *

    *

    !'()*#+0"0*#54*2

  • 8/10/2019 Java Design Pattern eBook

    65/132

    !#$%&'()*+,-.$/ 0(1+ :/$2 "#$

    =; 0)C*5&.*5 4&..)5-

    Decorator design patternis used to modify the functionality of an object atruntime. At the same time other instances of the same class will not beaffected by this, so individual object gets the modified behavior. Decoratordesign pattern is one of the structural design pattern (such as AdapterPattern, Bridge Pattern, Composite Pattern) and uses abstract classes orinterface withcompositionto implement.

    We use inheritanceor composition to extend the behavior of an object butthis is done at compile time and its applicable to all the instances of theclass. We cant add any new functionality of remove any existing behavior

    at runtimethis is when Decorator pattern comes into picture.

    Suppose we want to implement different kinds of cars we can createinterface Car to define the assemble method and then we can have a Basiccar, further more we can extend it to Sports car and Luxury Car. Theimplementation hierarchy will look like below image.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1491/bridge-pattern-in-java-example-tutorialhttp://www.journaldev.com/1491/bridge-pattern-in-java-example-tutorialhttp://www.journaldev.com/1535/composite-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1535/composite-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1325/what-is-composition-in-java-java-composition-examplehttp://www.journaldev.com/1325/what-is-composition-in-java-java-composition-examplehttp://www.journaldev.com/1325/what-is-composition-in-java-java-composition-examplehttp://www.journaldev.com/644/inheritance-in-java-examplehttp://www.journaldev.com/644/inheritance-in-java-examplehttp://www.journaldev.com/644/inheritance-in-java-examplehttp://www.journaldev.com/1325/what-is-composition-in-java-java-composition-examplehttp://www.journaldev.com/1535/composite-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1491/bridge-pattern-in-java-example-tutorialhttp://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorialhttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    66/132

    !#$%&'()*+,-.$/ 0(1+ :9$2 "#$

    But if we want to get a car at runtime that has both the features of sports carand luxury car, then the implementation gets complex and if further more wewant to specify which features should be added first, it gets even morecomplex. Now image if we have ten different kind of cars, theimplementation logic using inheritance and composition will be impossibleto manage. To solve this kind of programming situation, we apply decorator

    pattern.

    We need to have following types to implement decorator design pattern.

    >; ,*MN*-)-. @-.)5+&C)

    The interface or abstract class defining the methods that will beimplemented. In our case Carwill be the component interface.

    !"#$"%&"#$%'()*+,-.%,-/01)%,-"#(*2#(3

    !'()*#*/0&-6"#&F"-4

    !'()*#54*2"++&

    B; ,*MN*-)-. @MN()M)-.&.2*-

    The basic implementation of the component interface. We can haveBasicCar class as our component implementation.

    !"#$"%&"#$%'()*+,-.%,-/01)%,-"#(*2#(3

    !'()*##)"++8"+*#F"-*

    VR5&--*2&

    !'()*#54*2"++&

  • 8/10/2019 Java Design Pattern eBook

    67/132

    !#$%&'()*+,-.$/ 0(1+ ::$2 "#$

    ,; 0)C*5&.*5

    Decorator class implements the component interface and it has a HAS-Arelationship with the component interface. The component variable should

    be accessible to the child decorator classes, so we will make this variableprotected.

    !"#$"%&"#$%'()*+,-.%,-/01)%,-"#(*2#(3

    !'()*##)"++F"-A-"04-*

    !-40&2L*( "*(3

    !'()*#F"-A-"04-:L*( ";40:*+%"*(9"3

    >

    VR5&--*2&

    !'()*#54*2"++&

    VR5&--*2&

    !'()*#54*2"++&

  • 8/10/2019 Java Design Pattern eBook

    68/132

    !#$%&'()*+,-.$/ 0(1+ :=$2 "#$

    8G/2-$%#'2%=(0)2:E K,,0)1 B-*2'(-/ #B 8=#(2/ L*(%E;3

    >

    >

    !"#$"%&"#$%'()*+,-.%,-/01)%,-"#(*2#(3

    !'()*##)"++>'='-9F"-&=0&/2+L*(R-"#(*2#( 4

    !'()*#>'='-9F"-:L*( ";4

    +'!&-:";3

    >

    VR5&--*2&

    !'()*#54*2"++&

  • 8/10/2019 Java Design Pattern eBook

    69/132

    !#$%&'()*+,-.$/ 0(1+ :E$2 "#$

    ?; 0)C*5&.*5 4&..)5- ,(2)-. 45*35&M

    !"#$"%&"#$%'()*+,-.%,-/01)%2-/23

    *

    *

    /=#(2/L*(%*//-$A+-:;3

    8G/2-$%#'2%=(0)2+):Es)qqqqqE;3

    L*( /=#(2/F'C'(GL*( 9/&78=#(2/L*(:/&7F'C'(GL*(:/&7

    ?*/0"L*(:;;;3

    /=#(2/F'C'(GL*(%*//-$A+-:;3

    >

    >

    Notice that client program can create different kinds of Object at runtime

    and they can specify the order of execution too.

    Output of above test program is:

    ?*/0" L*(%K,,0)1 B-*2'(-/ #B 8=#(2/ L*(%

    qqqqq

    ?*/0" L*(%K,,0)1 B-*2'(-/ #B F'C'(G L*(%K,,0)1 B-*2'(-/ #B 8=#(2/

    L*(%

    O; @MN*5.&-. 4*2-.1

    Decorator pattern is helpful in providing runtime modification

    abilities and hence more flexible. Its easy to maintain and extendwhen the number of choices are more.

    The disadvantage of decorator pattern is that it uses a lot of similarkind of objects (decorators).

    Decorator pattern is used a lot inJava IOclasses, such asFileReader,BufferedReaderetc.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/942/java-io-tutorialhttp://www.journaldev.com/942/java-io-tutorialhttp://www.journaldev.com/942/java-io-tutorialhttp://www.journaldev.com/867/how-to-read-file-in-java-using-bufferedreader-scanner-files-with-encoding-support-and-filereaderhttp://www.journaldev.com/867/how-to-read-file-in-java-using-bufferedreader-scanner-files-with-encoding-support-and-filereaderhttp://www.journaldev.com/867/how-to-read-file-in-java-using-bufferedreader-scanner-files-with-encoding-support-and-filereaderhttp://www.journaldev.com/867/how-to-read-file-in-java-using-bufferedreader-scanner-files-with-encoding-support-and-filereaderhttp://www.journaldev.com/867/how-to-read-file-in-java-using-bufferedreader-scanner-files-with-encoding-support-and-filereaderhttp://www.journaldev.com/867/how-to-read-file-in-java-using-bufferedreader-scanner-files-with-encoding-support-and-filereaderhttp://www.journaldev.com/942/java-io-tutorialhttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    70/132

    !#$%&'()*+,-.$/ 0(1+ :H$2 "#$

    B)I&72*5&( 0)123- 4&..)5-1

    Behavioral patterns provide solution for the better interaction betweenobjects and how to provide lose coupling and flexibility to extend easily.

    "; %)MN(&.) Z).I*J 4&..)5-

    Template Methodis a behavioral design patternand its used to create amethod stub and deferring some of the steps of implementation to the

    subclasses. Template methoddefines the steps to execute an algorithm andit can provide default implementation that might be common for all or someof the subclasses.

    Lets understand this pattern with an example, suppose we want to provide

    an algorithm to build a house. The steps need to be performed to build ahouse are building foundation, building pillars, building walls andwindows. The important point is that we cant change the order of executionbecause we cant build windows before building the foundation. So in this

    case we can create a template method that will use different methods to buildthe house.

    Now building the foundation for a house is same for all type of houses,whether its a wooden house or a glass house. So we can provide baseimplementation for this, if subclasses want to override this method, they canbut mostly its common for all the types of houses.

    To make sure that subclasses dont override the template method, we should

    make it final.

    >; %)MN(&.) Z).I*J >'1.5&C. ,(&11

    Since we want some of the methods to be implemented by subclasses, wehave to make our base class asabstract class.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/1582/abstract-class-in-java-with-examplehttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    71/132

    !#$%&'()*+,-.$/ 0(1+ =K$2 "#$

    !"#$"%&"#$%'()*+,-.%,-/01)%2-$=+*2-3

    !'()*#"(+0-"#0#)"++C4'+&?&

    A'0+,W#'),*20#):;3

    A'0+,I0++*(/:;3

    A'0+,m*++/:;3

    A'0+,m0),#Q/:;3

    8G/2-$%#'2%=(0)2+):EM#'/- 0/ A'0+2%E;3

    >

  • 8/10/2019 Java Design Pattern eBook

    72/132

    !#$%&'()*+,-.$/ 0(1+ ="$2 "#$

    !'()*#54*2('*)2]"))+:;4

    8G/2-$%#'2%=(0)2+):E?'0+,0)1 m##,-) m*++/E;3

    >

    VR5&--*2&

    !'()*#54*2('*)2B*))"-+:;48G/2-$%#'2%=(0)2+):E?'0+,0)1 I0++*(/ Q02D m##, "#*20)1E;3

    >

    >

    We could have overridden other methods also, but for simplicity I am notdoing that.

    !"#$"%&"#$%'()*+,-.%,-/01)%2-$=+*2-3

    !'()*##)"++X)"++C4'+&&=0&/2+M#'/-H-$=+*2- 4

    VR5&--*2&

    !'()*#54*2('*)2]"))+:;4

    8G/2-$%#'2%=(0)2+):E?'0+,0)1 ^+*// m*++/E;3

    >

    VR5&--*2&

    !'()*#54*2('*)2B*))"-+:;4

    8G/2-$%#'2%=(0)2+):E?'0+,0)1 I0++*(/ Q02D 1+*// "#*20)1E;3

    >

    >

    ,; %)MN(&.) Z).I*J 4&..)5- ,(2)-.

    Lets test our template methodpattern example with a test program.

    !"#$"%&"#$%'()*+,-.%,-/01)%2-$=+*2-3

    !'()*##)"++C4'+*/%F)*&/04

    !'()*#+0"0*#54*2

  • 8/10/2019 Java Design Pattern eBook

    73/132

    !#$%&'()*+,-.$/ 0(1+ =$$2 "#$

    >

    Notice that client is invoking the template method of base class anddepending of implementation of different steps, its using some of the

    methods from base class and some of them from subclass.

    Output of the above program is:?'0+,0)1 B#'),*20#) Q02D "-$-)2X0(#) (#,/ *), /*),

    ?'0+,0)1 I0++*(/ Q02D m##, "#*20)1

    ?'0+,0)1 m##,-) m*++/

    ?'0+,0)1 ^+*// m0),#Q/

    M#'/- 0/ A'0+2%

    qqqqqqqqqqqq

    ?'0+,0)1 B#'),*20#) Q02D "-$-)2X0(#) (#,/ *), /*),

    ?'0+,0)1 I0++*(/ Q02D 1+*// "#*20)1

    ?'0+,0)1 ^+*// m*++/

    ?'0+,0)1 ^+*// m0),#Q/M#'/- 0/ A'0+2%

    0; %)MN(&.) Z).I*J ,(&11 02&35&M

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    74/132

    !#$%&'()*+,-.$/ 0(1+ =#$2 "#$

    ?; %)MN(&.) Z).I*J 4&..)5- 2- U0V

    All non-abstract methods of java.io.InputStream,java.io.OutputStream, java.io.Reader and java.io.Writer.

    All non-abstract methods of java.util.AbstractList,java.util.AbstractSet and java.util.AbstractMap.

    O; @MN*5.&-. 4*2-.1

    Template method should consists of certain steps whose order is fixedand for some of the methods, implementation differs from base classto subclass. Template method should be final.

    Most of the times, subclasses calls methods from super class but intemplate pattern, superclass template method calls methods fromsubclasses, this is known as Hollywood Principle dont call us,well call you.

    Methods in base class with default implementation are referred as

    Hooks and they are intended to be overridden by subclasses, if youwant some of the methods to be not overridden, you can make themfinal, for example in our case we can make buildFoundation() methodfinal because if we dont want subclasses to override it.

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://en.wikipedia.org/wiki/Hollywood_principlehttp://en.wikipedia.org/wiki/Hollywood_principlehttp://en.wikipedia.org/wiki/Hollywood_principlehttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    75/132

    !#$%&'()*+,-.$/ 0(1+ =/$2 "#$

    $; Z)J2&.*5 4&..)5-

    Mediator Patternis one of the behavioral design pattern, so it deals with

    the behaviors of objects. Mediator design pattern is used to provide acentralized communication medium between different objects in a system.According to GoF, mediator pattern intent is:

    Mediator design pattern is very helpful in an enterprise application wheremultiple objects are interacting with each other. If the objects interact witheach other directly, the system components are tightly-coupled with eachother that makes maintainability cost higher and not flexible to extendeasily. Mediator pattern focuses on provide a mediator between objects forcommunication and help in implementing lose-coupling between objects.

    Air traffic controller is a great example of mediator pattern where the airport

    control room works as a mediator for communication between differentflights. Mediator works as a router between objects and it can have its own

    logic to provide way of communication.

    The system objects that communicate each other are called Colleagues.Usually we have an interface or abstract classthat provides the contract forcommunication and then we have concrete implementation of mediators.

    For our example, we will try to implement a chat application where userscan do group chat. Every user will be identified by its name and they can

    send and receive messages. The message sent by any user should be receivedby all the other users in the group.

    Allows loose coupling by encapsulating the waydisparate sets of objects interact and communicate witheach other. Allows for the actions of each object set tovar inde endentl of one another

    http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/http://www.journaldev.com/1607/difference-between-abstract-class-and-interface-in-javahttp://www.journaldev.com/1607/difference-between-abstract-class-and-interface-in-javahttp://www.journaldev.com/1607/difference-between-abstract-class-and-interface-in-javahttp://www.journaldev.com/
  • 8/10/2019 Java Design Pattern eBook

    76/132

    !#$%&'()*+,-.$/ 0(1+ =9$2 "#$

    >; Z)J2&.*5 @-.)5+&C)

    First of all we will create Mediator interface that will define the contract for

    concrete mediators.!"#$"%&"#$%'()*+,-.%,-/01)%$-,0*2#(3

    !'()*#*/0&-6"#&F:"0U&2*"04-4

    !'()*#54*2+&/2U&++"%&:82(0)1 $/1XU/-( '/-(;3

    54*2"22@+&-:U/-( '/-