Design Pattern JHB

Embed Size (px)

Citation preview

  • 8/17/2019 Design Pattern JHB

    1/118

    Design Patterns

  • 8/17/2019 Design Pattern JHB

    2/118

    Outline

    • Introduction

    • Definition and History

    Types of Design Patterns• Creational Patterns

     – Factory Pattern

     –

    Singleton Pattern – Prototype Pattern

  • 8/17/2019 Design Pattern JHB

    3/118

    Book

    http://www.sws.bfh.ch/~amrhein/ADP/HeadFirstDesignPatterns.pdf

  • 8/17/2019 Design Pattern JHB

    4/118

    Introduction

    • Design patterns represent the best practicesused by experienced object-oriented softwaredevelopers.

    • Design patterns are solutions to generalproblems that software developers facedduring software development.

    These solutions were obtained by trial anderror by numerous software developers overquite a substantial period of time.

  • 8/17/2019 Design Pattern JHB

    5/118

    Definition

    • A pattern is a recurring solution to a standardproblem, in a context.

    • “A pattern describes a problem which occurs

    over and over again in our environment, andthen describes the core of the solution to thatproblem, in such a way that you can use thissolution a million times over, without everdoing it the same way twice.” ( ChristopherAlexander)

  • 8/17/2019 Design Pattern JHB

    6/118

    Why Patterns ?

    • Mature engineering disciplines have

    handbooks describing successful solutions

    to known problems

    • Automobile designers don't design cars

    from scratch using the laws of physics

    • Instead, they reuse standard designs with

    successful track records, learning from

    experience

  • 8/17/2019 Design Pattern JHB

    7/118

    Some History

    • Started in 1987 by Ward Cunningham and KenBeck who were working with Smalltalk anddesigning GUIs.

    • Popularized by Gamma, Helm, Johnson and

    Vlissides (The gang of four, Go4)• The three of Go4 were working on frameworks 

    (E++,Unidraw, HotDraw)• Design pattern use a consistent documentation

    approach• Design pattern are granular and applied at

    different levels such as frameworks, subsystemsand sub-subsystems

  • 8/17/2019 Design Pattern JHB

    8/118

    Elements of Design Pattern

    • Design patterns have 4 essential elements:

     – Pattern name: increases vocabulary of designers

     – Problem: intent, context, when to apply

     – Solution: UML-like structure, abstract code

     – Consequences: results and tradeoffs

  • 8/17/2019 Design Pattern JHB

    9/118

    Categorizing Pattern

    Patterns, then, represent expert solutions to

    recurring problems in a context and thus have

    been captured at many levels of abstraction

    and in numerous domains. Numerous

    categories are:

    • Creational

    • Structural

    • Behavioral

  • 8/17/2019 Design Pattern JHB

    10/118

    Creational Patterns

    • These design patterns provide a way to create

    objects while hiding the creation logic.

    • This gives program more flexibility in deciding

    which objects need to be created for a given

    use case.

  • 8/17/2019 Design Pattern JHB

    11/118

    Structural Pattern

    • In Software Engineering, Structural Design

    Patterns are Design Patterns that ease the

    design by identifying a simple way to realize

    relationships between entities.

  • 8/17/2019 Design Pattern JHB

    12/118

    Behavioral Pattern

    • These design patterns are specifically

    concerned with communication between

    objects.

  • 8/17/2019 Design Pattern JHB

    13/118

    Creational Patterns

  • 8/17/2019 Design Pattern JHB

    14/118

    Factory Pattern

    • Factory pattern is one of most used design

    pattern in Java.

    • In Factory pattern, we create object without

    exposing the creation logic to the client and

    refer to newly created object using a common

    interface.

  • 8/17/2019 Design Pattern JHB

    15/118

    Example

  • 8/17/2019 Design Pattern JHB

    16/118

    Description

    • We're going to create a Shape interface andconcrete classes implementingtheShape interface. A factory

    class ShapeFactory  is defined as a next step.•   FactoryPatternDemo, our demo class will

    use ShapeFactory  to get a Shapeobject. It willpass information (CIRCLE / RECTANGLE /SQUARE ) toShapeFactory  to get the type ofobject it needs.

  • 8/17/2019 Design Pattern JHB

    17/118

    Implementation

  • 8/17/2019 Design Pattern JHB

    18/118

  • 8/17/2019 Design Pattern JHB

    19/118

  • 8/17/2019 Design Pattern JHB

    20/118

  • 8/17/2019 Design Pattern JHB

    21/118

    Advantages / Use

    •  New shapes can be added without changing a

    single line of code in the framework(the client

    code that uses the shapes from the factory)

  • 8/17/2019 Design Pattern JHB

    22/118

    Singleton Pattern

    • This pattern involves a single class which is

    responsible to create an object while making

    sure that only single object gets created. This

    class provides a way to access its only objectwhich can be accessed directly without need

    to instantiate the object of the class.

  • 8/17/2019 Design Pattern JHB

    23/118

    Example

  • 8/17/2019 Design Pattern JHB

    24/118

  • 8/17/2019 Design Pattern JHB

    25/118

  • 8/17/2019 Design Pattern JHB

    26/118

    Use of Singleton Patterns

    •  It is useful when exactly one object is needed tocoordinate actions across the system.

    • This is one of the most commonly used patterns. Thereare some instances in the application where we have to

    use just one instance of a particular class. Let’s take upan example to understand this.

    • A very simple example is say Logger, suppose we needto implement the logger and log it to some fileaccording to date time. In this case, we cannot have

    more than one instances of Logger in the applicationotherwise the file in which we need to log will becreated with every instance.

  • 8/17/2019 Design Pattern JHB

    27/118

    Prototype Pattern

    • Prototype pattern refers to creating duplicate

    object while keeping performance in mind.

    • This pattern involves implementing a

    prototype interface which tells to create a

    clone of the current object.

    • This pattern is used when creation of object

    directly is costly.

  • 8/17/2019 Design Pattern JHB

    28/118

    Clonable Interface

    • The Cloneable interface defines no members.

    It is used to indicate that a class allows abitwise copy of an object (that is, a clone) to

    be made.

    •  If you try to call clone( ) on a class that does

    not implementCloneable,

    a CloneNotSupportedException is thrown

  • 8/17/2019 Design Pattern JHB

    29/118

    Description

    • We're going to create an abstract class Shape (

    Which implements Clonable interface) and

    concrete classes extending the Shape class. A

    class ShapeCache is defined as a next stepwhich stores shape objects in a Hashtable and

    returns their clone when requested.

    •   PrototypPatternDemo, our demo class willuse ShapeCache class to get a Shapeobject.

  • 8/17/2019 Design Pattern JHB

    30/118

    Example

  • 8/17/2019 Design Pattern JHB

    31/118

    Implementation

  • 8/17/2019 Design Pattern JHB

    32/118

  • 8/17/2019 Design Pattern JHB

    33/118

  • 8/17/2019 Design Pattern JHB

    34/118

  • 8/17/2019 Design Pattern JHB

    35/118

    Application

    • If you have a requirement , where you need topopulate or use a same data containing Objectrepeatable and it is not possible to build fromexisting Object.

    • To build an Object is time consuming [Building aBig Object , by getting data from Database] thenuse this design pattern , as in this a Copy the

    existing Object is created ,this copy would bedifferent from the Original Object and could beused just like Original one.

  • 8/17/2019 Design Pattern JHB

    36/118

    Example

    • The walls, rooms, doors and

    other elements of a video game

    are simply repeated in

    different arrangements.

    • To ensure smooth experience,

    a quick way to generate a haze

    map is required.

  • 8/17/2019 Design Pattern JHB

    37/118

    What is the difference between

    Factory Design pattern and Prototype

    Pattern ?

  • 8/17/2019 Design Pattern JHB

    38/118

    Object Pool Pattern

    • The object pool pattern is a software creationaldesign pattern that uses a set ofinitialized objects kept ready to use – a "pool" – rather than allocating and destroying them ondemand.

    • A client of the pool will request an object fromthe pool and perform operations on the returned

    object. When the client has finished, it returnsthe object to the pool rather than destroying it;this can be done manually or automatically.

  • 8/17/2019 Design Pattern JHB

    39/118

    Object Pool

    • When it is necessary to work with a large

    number of objects that are particularly

    expensive to instantiate and each object is

    only needed for a short period of time, theperformance of an entire application may be

    adversely affected. An object pool design

    pattern may be deemed desirable in casessuch as these.

  • 8/17/2019 Design Pattern JHB

    40/118

    Example

    • One example is the .NET Framework DataProvider for SQL Server. As SQL Serverdatabase connections can be slow to create, a

    pool of connections is maintained. When youclose a connection it does not actuallyrelinquish the link to SQL Server. Instead, theconnection is held in a pool from which it can

    be retrieved when requesting a newconnection. This substantially increases thespeed of making connections.

  • 8/17/2019 Design Pattern JHB

    41/118

    Implementation

    • Java supports thread

    pooling via java.util.concurrent.ExecutorServic

    e and other related classes. The executor

    service has a certain number of "basic"threads that are never discarded. If all threads

    are busy, the service allocates the allowed

    number of extra threads that are laterdiscarded if not used for the certain expiration

    time.

  • 8/17/2019 Design Pattern JHB

    42/118

    Builder Pattern

    • Separate the construction of a complex object

    from its representation so that the same

    construction process can create different

    representations.

  • 8/17/2019 Design Pattern JHB

    43/118

    • Builder focuses on constructing a complex

    object step by step. Factory emphasizes a

    family of product objects (either simple or

    complex).

    • Builder returns the product as a final step, but

    as far as the Abstract Factory is concerned, the

    product gets returned immediately.

  • 8/17/2019 Design Pattern JHB

    44/118

    Example

  • 8/17/2019 Design Pattern JHB

    45/118

  • 8/17/2019 Design Pattern JHB

    46/118

  • 8/17/2019 Design Pattern JHB

    47/118

  • 8/17/2019 Design Pattern JHB

    48/118

  • 8/17/2019 Design Pattern JHB

    49/118

  • 8/17/2019 Design Pattern JHB

    50/118

  • 8/17/2019 Design Pattern JHB

    51/118

  • 8/17/2019 Design Pattern JHB

    52/118

    Structural Patterns

  • 8/17/2019 Design Pattern JHB

    53/118

    Structural Patterns

    • In Software Engineering, Structural Design

    Patterns are Design Patterns that ease the

    design by identifying a simple way to realize

    relationships between entities.

  • 8/17/2019 Design Pattern JHB

    54/118

    Adapter Pattern

    • Adapter pattern works as a bridge between

    two incompatible interfaces.

    • This type of design pattern comes under

    structural pattern as this pattern combines the

    capability of two independent interfaces.

  • 8/17/2019 Design Pattern JHB

    55/118

    Adapter Pattern

    • This pattern involves a single class which is

    responsible to join functionalities of

    independent or incompatible interfaces.

    • A real life example could be a case of card

    reader which acts as an adapter between

    memory card and a laptop.

  • 8/17/2019 Design Pattern JHB

    56/118

    Example

  • 8/17/2019 Design Pattern JHB

    57/118

    • We have a MediaPlayer   interface and aconcrete class  AudioPlayer implementingthe MediaPlayer   interface.  AudioPlayer   can

    play mp3 format audio files by default.• We are having another

    interface  AdvancedMediaPlayer   and concreteclasses implementing

    the  AdvancedMediaPlayer   interface. Theseclasses can play vlc and mp4 format files.

  • 8/17/2019 Design Pattern JHB

    58/118

    • We want to make AudioPlayer  to play other formats aswell. To attain this, we have created an adapterclass MediaAdapter   which implementstheMediaPlayer   interface and

    uses  AdvancedMediaPlayer   objects to play therequired format.

    •   AudioPlayer   uses the adapterclass MediaAdapter   passing it the desired audio type

    without knowing the actual class which can play thedesired format. AdapterPatternDemo, our demo classwill use AudioPlayer  class to play various formats.

  • 8/17/2019 Design Pattern JHB

    59/118

  • 8/17/2019 Design Pattern JHB

    60/118

  • 8/17/2019 Design Pattern JHB

    61/118

  • 8/17/2019 Design Pattern JHB

    62/118

  • 8/17/2019 Design Pattern JHB

    63/118

  • 8/17/2019 Design Pattern JHB

    64/118

    Proxy Pattern

    • In proxy pattern, a class represents

    functionality of another class. This type of

    design pattern comes under structural

    pattern.• A proxy is a wrapper or agent object that is

    being called by the client to access the real

    serving object behind the scenes

  • 8/17/2019 Design Pattern JHB

    65/118

    Example

    • We are going to create an Image interface and

    concrete classes implementing

    the Image interface. ProxyImage is a a proxy

    class to reduce memory footprintof RealImage object loading.

    •   ProxyPatternDemo, our demo class, will

    use ProxyImage to get an Imageobject to loadand display as it needs.

  • 8/17/2019 Design Pattern JHB

    66/118

  • 8/17/2019 Design Pattern JHB

    67/118

  • 8/17/2019 Design Pattern JHB

    68/118

  • 8/17/2019 Design Pattern JHB

    69/118

  • 8/17/2019 Design Pattern JHB

    70/118

    Usage : Remote Proxy

    •  In distributed object communication, a local

    object represents a remote object (one that

    belongs to a different address space). The

    local object is a proxy for the remote object,and method invocation on the local object

    results in remote method invocation on the

    remote object.

  • 8/17/2019 Design Pattern JHB

    71/118

    Usage : Virtual Proxy

    • In place of a complex or heavy object, use a

    skeleton representation. When an underlying

    image is huge in size, just represent it using a

    virtual proxy object and on demand load thereal object.

  • 8/17/2019 Design Pattern JHB

    72/118

    Usage : Protection Proxy

    • Example of Proxy server in internet usage.

  • 8/17/2019 Design Pattern JHB

    73/118

    Decorator Pattern

  • 8/17/2019 Design Pattern JHB

    74/118

    Decorator Pattern

    • Decorator pattern allows a user to add newfunctionality to an existing object withoutaltering its structure. This type of design

    pattern comes under structural pattern as thispattern acts as a wrapper to existing class.

    • Attach additional responsibilities to an objectdynamically. Decorators provide a flexible

    alternative to subclassing for extendingfunctionality.

  • 8/17/2019 Design Pattern JHB

    75/118

    Decorator Pattern

    • This pattern creates a decorator class which

    wraps the original class and provides

    additional functionality keeping class methods

    signature intact.

  • 8/17/2019 Design Pattern JHB

    76/118

    Scenario

  • 8/17/2019 Design Pattern JHB

    77/118

    With Decorator Pattern

  • 8/17/2019 Design Pattern JHB

    78/118

    Scenario

    h

  • 8/17/2019 Design Pattern JHB

    79/118

    With Decorator Pattern

    l

  • 8/17/2019 Design Pattern JHB

    80/118

    Example

    l

  • 8/17/2019 Design Pattern JHB

    81/118

    Example

    E l

  • 8/17/2019 Design Pattern JHB

    82/118

    Example

    E l

  • 8/17/2019 Design Pattern JHB

    83/118

    Example

    E l

  • 8/17/2019 Design Pattern JHB

    84/118

    Example

    E l

  • 8/17/2019 Design Pattern JHB

    85/118

    Example

    F d P tt

  • 8/17/2019 Design Pattern JHB

    86/118

    Facade Pattern

    • Facade pattern hides the complexities of thesystem and provides an interface to the client

    using which the client can access the system.

    This type of design pattern comes understructural pattern as this pattern adds an

    interface to existing system to hide its

    complexities.

  • 8/17/2019 Design Pattern JHB

    87/118

    • This pattern involves a single class whichprovides simplified methods required by client

    and delegates calls to methods of existing

    system classes.

  • 8/17/2019 Design Pattern JHB

    88/118

  • 8/17/2019 Design Pattern JHB

    89/118

    E l

  • 8/17/2019 Design Pattern JHB

    90/118

    Example

  • 8/17/2019 Design Pattern JHB

    91/118

  • 8/17/2019 Design Pattern JHB

    92/118

  • 8/17/2019 Design Pattern JHB

    93/118

  • 8/17/2019 Design Pattern JHB

    94/118

  • 8/17/2019 Design Pattern JHB

    95/118

    Behavioral Pattern

    Observer Pattern

  • 8/17/2019 Design Pattern JHB

    96/118

    Observer Pattern

    • Observer pattern is used when there is one-to-many relationship between objects such as

    if one object is modified, its depenedent

    objects are to be notified automatically

    Cont

  • 8/17/2019 Design Pattern JHB

    97/118

    Cont.

    • Observer pattern uses three actor classes.

    • Subject, Observer and Client.

    • Subject is an object having methods to attach

    and detach observers to a client object.

    • We have created an abstract

    class Observer  and a concrete

    classSubject  that is extending class Observer .

    Example

  • 8/17/2019 Design Pattern JHB

    98/118

    Example

  • 8/17/2019 Design Pattern JHB

    99/118

  • 8/17/2019 Design Pattern JHB

    100/118

  • 8/17/2019 Design Pattern JHB

    101/118

  • 8/17/2019 Design Pattern JHB

    102/118

    Output

  • 8/17/2019 Design Pattern JHB

    103/118

    Output

    Example

  • 8/17/2019 Design Pattern JHB

    104/118

    Example

    Mediator Pattern

  • 8/17/2019 Design Pattern JHB

    105/118

    Mediator Pattern

    • Mediator pattern is used to reducecommunication complexity between multiple

    objects or classes.

    • Mediator pattern is used to reduce

    communication complexity between multiple

    objects or classes.

    Example

  • 8/17/2019 Design Pattern JHB

    106/118

    Example

    • We are demonstrating mediator pattern byexample of a chat room where multiple users

    can send message to chat room and it is the

    responsibility of chat room to show themessages to all users. We have created two

    classesChatRoom and User . User  objects will

    use ChatRoom method to share their

    messages.

    Example

  • 8/17/2019 Design Pattern JHB

    107/118

    Example

    Example

  • 8/17/2019 Design Pattern JHB

    108/118

    Example

    Example

  • 8/17/2019 Design Pattern JHB

    109/118

    Example

    Example

  • 8/17/2019 Design Pattern JHB

    110/118

    Example

    Memento Pattern

  • 8/17/2019 Design Pattern JHB

    111/118

    Memento Pattern

    • Memento pattern is used to restore state ofan object to a previous state.

    • The client requests a Memento from thesource object when it needs to checkpoint the

    source object's state.

    Memento Pattern

  • 8/17/2019 Design Pattern JHB

    112/118

    Memento Pattern

    • Memento pattern uses three actor classes.Memento contains state of an object to be

    restored. Originator creates and stores states

    in Memento objects and Caretaker object isresponsible to restore object state from

    Memento. We have created

    classes Memento, Originator  and CareTaker  

    Memento Pattern

  • 8/17/2019 Design Pattern JHB

    113/118

    Memento Pattern

    •   Originator  - the object that knows how to saveitself.

    •   Caretaker  - the object that knows why and

    when the Originator needs to save and restoreitself.

    •   Memento - the lock box that is written and

    read by the Originator, and guided by theCaretaker.

    Example

  • 8/17/2019 Design Pattern JHB

    114/118

    Example

  • 8/17/2019 Design Pattern JHB

    115/118

  • 8/17/2019 Design Pattern JHB

    116/118

  • 8/17/2019 Design Pattern JHB

    117/118

  • 8/17/2019 Design Pattern JHB

    118/118