g of design patterns

Upload: nikimegs

Post on 04-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 g of Design Patterns

    1/54

    Gang of Four Design Patterns

    An Introduction to Pattern-BasedObject-Oriented Design

  • 7/31/2019 g of Design Patterns

    2/54

    Gang of Four

    o Pattern-based design was introduced intoarchitecture and engineering in the 1950's

    o Almost immediately, software engineers

    began using patterns for designing softwareo It wasn't until a group of four researchers

    combined forces that pattern-based designbecame well-known and commonplace

    o This group was known as the gang of four (GoF)

  • 7/31/2019 g of Design Patterns

    3/54

    Gang of Four

    o The gang of four (GoF) is:

    o Erich Gammao Richard Helm

    o Ralph Johnson

    o John Vlissides

    o They are the authors of the famoustext "Design Patterns: Elements ofReusable Object-Oriented Software"

  • 7/31/2019 g of Design Patterns

    4/54

    Pattern Quotes

    o A pattern is an idea that has been

    useful in one practical context andwill probably be useful in others

    o Martin Fowler

    o A pattern is a three-part rule, whichexpresses a relation between acertain context, a problem, and asolution

    o Christopher Alexander

  • 7/31/2019 g of Design Patterns

    5/54

    Design Pattern Advantages

    o Using patterns offers a few key

    advantages:o Leverage a proven solution

    o Provide a common vocabulary

  • 7/31/2019 g of Design Patterns

    6/54

    Leverage a Proven Solutiono The solution for a pattern has been

    designed, implemented and testedo Reusing these solutions allows most of

    each of these steps to be eliminated

    o If the implementation of a pattern is used,the design, implementation, and testingare minimal just to ensure the properbehaviour exists

    o If the design of a pattern is used, thesolution specific to the problem must be

    implemented and tested, but need notbe redesigned

  • 7/31/2019 g of Design Patterns

    7/54

    Provide a Common Vocabulary

    o Some patterns are very common

    o Documenting and cataloguing patternsallows designers and architects todescribe a solution using patterns as partof the language

    o Typically, this can make descriptions ofsolutions shorter

    o Architects and designers can more easilycommunicate their designs to theirdevelopers

  • 7/31/2019 g of Design Patterns

    8/54

    Creational Design Patterns

    o There are many design patterns

    that relate to the creation ofobjects

    o In this class, we will focus on

    three important patterns:o Singleton

    o Abstract Factory

    o Prototype

  • 7/31/2019 g of Design Patterns

    9/54

    The Singleton Patterno The Singleton creates a single

    instance of an object, but allowsmultiple users to access it

    o e.g. Consider a class that representsthe connection to a database

    o Creating only one connection to adatabase and re-using it in various partsof the program makes sense

  • 7/31/2019 g of Design Patterns

    10/54

    The Singleton Pattern

    o When to use the Singleton

    pattern:o When there should be only one

    instance of a class, and it must be

    accessible to clients from a well-known access point

  • 7/31/2019 g of Design Patterns

    11/54

    Singleton Pattern: Exampleo A class (Configuration) maintains the

    applications configurationo The configuration is also stored in an XML file by

    this class

    o Many objects may wish to read and update theconfiguration

    o Multiple simultaneous reads are not a problem

    o However, we do not want multiple simultaneouswrites

    o The class can use the synchronized keyword toblock concurrent access

    o A singleton class will ensure that all of theapplications objects can get the same copy of thisclass

  • 7/31/2019 g of Design Patterns

    12/54

    Singleton Pattern: Examplepublic class ConfigurationSingleton {

    public static Configuration instance = null;

    public static Configuration getInstance() {

    if (instance == null)

    instance = new Configuration();

    return instance;

    }}

  • 7/31/2019 g of Design Patterns

    13/54

    The Abstract Factory Patterno The Idea: To provide means to create

    families of related or dependent objectswithout specifying their concrete classes

    o e.g. Consider a factory class that createsbuttonso Users can use this factory to create various kinds

    of buttons for their applicationo The factory object might determine (through the

    user's preferences) what kind of button to makeo Perhaps the button will be the Windows-style or

    UNIX-style button

    o Perhaps the colours of the button will be customized

    as per the users colour preferenceso The developer need not concern him/herself with

    these user-preference details, since they use thesame factory in all cases

  • 7/31/2019 g of Design Patterns

    14/54

    The Abstract Factory Patterno The Abstract Factory takes advantage of

    polymorphism to accomplish its tasko The user of an abstract factory requests an

    object of a specific type

    o The factory is actually a concrete factory,

    which knows how to create that onespecific object type

    o The factory returns the parent class, but thevalue is the correct descendant of this type

  • 7/31/2019 g of Design Patterns

    15/54

    The Abstract Factory Patterno Use the Abstract Factory when:

    o The system should be independent of how objectsare created, composed, and represented

    o The system should be configured with one of afamily of objects

    o How it works:

    o The Abstract Factory only determines whichConcrete Factory it will use

    o The Concrete Factory actually creates theappropriate object

    o Normally, the appropriate Concrete Factory isdetermined and created at run-time (once)

  • 7/31/2019 g of Design Patterns

    16/54

    Abstract Factory Pattern: Example

    o Abstract Factory: The main factory, which delegatesobject creation to one of the Concrete Factories

    o e.g. public abstract Button getInstance();

    o Concrete Factory (one per object type): Knows howto create one specific type of objecto e.g.

    public class UNIXButtonFactory extends ButtonFactory {

    public Button getInstance() {Button button = new UNIXButton();

    // UNIX-specific stuff for buttons here

    return button;

    }

    }

    ButtonFactory factory = ;

    Button button = factory.getInstance();

  • 7/31/2019 g of Design Patterns

    17/54

    Abstract Factory Example

    ButtonFactory

    getInstance()

    UNIXButtonFactory

    getInstance()

    WindowsButtonFactory

    getInstance()

    Userrequest

    Button

    UNIXButton WindowsButton

  • 7/31/2019 g of Design Patterns

    18/54

    The Prototype Patterno The Idea: Create a copy of a prototype

    object, and then customize ito e.g. Consider a UML tool that lets you add

    new classes, objects, methods, attributes

    o When a user creates a class, it has all defaultvalues (and no methods or attributes)

    o The user can then:

    o Rename the class

    o Modify class properties (e.g. abstract)

    o Add attributes

    oAdd methods

  • 7/31/2019 g of Design Patterns

    19/54

    Prototype: Example// initialize the prototypeUMLClass classPrototype = new UMLClass();

    classPrototype.setName(NewClass);classPrototype.setAttributes(new ArrayList());classPrototype.setMethods(new ArrayList());etc

    // create an instance, and customize itUMLClass newClass1 = (UMLClass)classPrototype.clone();newClass1.setName(Customer);newClass1.setAbstract(true);Attribute attribute1 = new Attribute();

    attribute1.setName(firstName);attribute1.setType(String);newClass1.getAttributes.add(attribute1);etc

  • 7/31/2019 g of Design Patterns

    20/54

    Prototype: Example

    BasePrototype

    clone()

    ClassPrototype

    clone()

    UseCasePrototype

    clone()

    User

  • 7/31/2019 g of Design Patterns

    21/54

    The Prototype Pattern

    o When to use the Prototype pattern:

    o When it makes sense to create classes inan identical (or similar) form, thencustomize them

  • 7/31/2019 g of Design Patterns

    22/54

    Structural Design Patterns

    o There are many design patterns that

    relate to the structure of (or staticrelationships between) objects

    o In this class, we will focus on threeimportant patterns:

    o Adapter

    o Faade

    o Proxy

  • 7/31/2019 g of Design Patterns

    23/54

    The Adapter Patterno The Idea: Allow one interface to operate

    like another interfaceo Thus one type of object can be used like another

    type of object

    o e.g. In Java, if you want to read bytes froma file, you use one of the 'XYZInputStream'

    classeso If you want to read characters (including multi-byte characters) from a file, you use one of the'XYZReader' classes

    o Any 'XYZInputStream' class can be treated like an'XYZReader' class by applying an adapter called

    'InputStreamReader' which converts bytes tocharacters

  • 7/31/2019 g of Design Patterns

    24/54

    The Adapter Pattern

    o Use adapters when:

    o You want to use an existing class (thatmeets your needs), but its interfacedoesn't match what you need

    o You want to create a reusable class that

    can cooperate with unrelated classes(some yet undeveloped)

    o Thus you cannot know in advance what therequired interfaces will be

  • 7/31/2019 g of Design Patterns

    25/54

    The Adapter Patterno An adapter is one of the most useful

    patternso This is because it allows seemingly different

    objects (which could be pattern-based) tooperate, even if their interfaces don't match

    o Adapters increase the reusability of all objects

    o Another example of an Adapter would be aprogram that sends input to and receivesoutput from a legacy applicationo This is typically done using standard in/out

    o This is done frequently to update old (butoperational and well-tested) software to includefeatures such as:

    o An updated GUI interface to a text-basedapplication

    o A web interface

  • 7/31/2019 g of Design Patterns

    26/54

    Adapter: Example

    o As an example, assume our

    company switches database vendorso Our software has isolated database

    operations to one module

    o That module makes calls to a well-known

    APIo Our new database has its own API, which

    has similar functionality

    o However, the interfaces are not the same

    o What do we do?

  • 7/31/2019 g of Design Patterns

    27/54

    Adapter: Example

    User

    NewDBAPI

    FindObject(String hashedKey)

    OldDBAPIInterface

    GetObject(String key)

    DBAdapter

    GetObject(String key)

  • 7/31/2019 g of Design Patterns

    28/54

    Adapter: Examplepublic class DBAdapter {

    public Object GetObject(String key) {

    String hashedKey = HashingUtils.hash(key);

    return FindObject(hashedKey);

    }

    }

    OldDBAPIInterface dbComponent = ;

    Config config = dbComponent.GetObject(config);

    Th F d P tt

  • 7/31/2019 g of Design Patterns

    29/54

    The Faade Pattern

    o The Idea: Provide a unified interface

    to a set of interfaces of a subsystemo When we have a number of lower-level

    classes that perform the function of somehigh-level interface, Faade acts as the

    high level interfaceo The Faade delegates each responsibility to

    the appropriate lower-level class

    Th F d P tt

  • 7/31/2019 g of Design Patterns

    30/54

    The Faade Patterno e.g. In your project, the Controller might be

    made of several different classeso Each of these classes might perform differenttasks

    o A Faade might be used to combine thefunctionality of these classes into a unified

    interface

    F d E l

  • 7/31/2019 g of Design Patterns

    31/54

    Faade: Example

    AccountService

    createAccount()

    deposit()

    withdraw()

    TransactionService

    addTransaction()

    LoanService

    applyForLoan()

    Faade

    createAccount()

    deposit()

    withdraw()addTransaction()

    applyForLoan()

    User

    F d E l

  • 7/31/2019 g of Design Patterns

    32/54

    Faade: Examplepublic class BankFaade {

    private AccountService accountService;private TransactionService transactionService;private LoanService loanService;public addAccount(Account account) {

    accountService.addAccount(account);}public deposit(int accountId, float amount) {

    accountService.deposit(accountId, amount);

    }public withdraw(int accountId, float amount) {

    accountService.withdraw(accountId, amount);}public addTransaction(Transaction tx) {

    transactionService.addTransaction(tx);}

    public applyForLoan(Customer cust, LoanDetails loan) {loanService.apply(cust, loan);

    }}

    Th F d P tt

  • 7/31/2019 g of Design Patterns

    33/54

    The Faade Pattern

    o Use the Faade pattern when:

    o You want to provide a unified interface toa more complex subsystem (of multipleclasses)

    o Faades decouple the client and

    subsystem, reducing theinterdependency (connascence)

    Th P P tt

  • 7/31/2019 g of Design Patterns

    34/54

    The Proxy Patterno A proxy object is a representative

    (delegate) for another object

    o There are several uses for proxies:o For controlling access to resources

    o i.e. implementing security through proxies

    o For creating virtual versions of objects

    o Where creating the real objects is (e.g.computationally) expensive

    o For access to remote objectso Where the real objects exist on other machines

    o For performing additional maintenanceo e.g. automatic garbage collection, synchronized

    access, loading objects from persistent storage

    Th P P tt

  • 7/31/2019 g of Design Patterns

    35/54

    The Proxy Patterno e.g. Enterprise JavaBeans and RMI

    provide an example of using proxieso A client for RMI or EJBs requests a proxyversion of an object

    o The proxy communicates (over thenetwork) with the actual object

    o The proxy object makes remotecommunication appear (almost)identical to a local connection

    P E l

  • 7/31/2019 g of Design Patterns

    36/54

    Proxy: Example

    AccountService{abstract}

    addAccount()

    deposit()

    withdraw()

    AccountServiceImpl

    addAccount()

    deposit()

    withdraw()

    AccountServiceProxy

    addAccount()

    deposit()

    withdraw()

    User

    P E l

  • 7/31/2019 g of Design Patterns

    37/54

    Proxy: Examplepublic class AccountServiceProxy

    implements AccountService {

    public void addAccount(Account account) {

    InvokeMessage message = new InvokeMessage();

    message.setMethodName(addAccount);

    message.setArgumentCount(0);

    byte[] serializedAccount = serialize(account);

    message.setArgument(0, serializedAccount);

    send(message);

    }

    private byte[] serialize(Account account) { }

    private void send(InvokeMessage message) { }

    }

    Th P P tt

  • 7/31/2019 g of Design Patterns

    38/54

    The Proxy Patterno The proxy object assembles data into a

    network message and sends it to the remoteobject

    o A remote receiver receives this data, andturns it into a local message that is sent tothe remote object

    Th P P tt

  • 7/31/2019 g of Design Patterns

    39/54

    The Proxy Pattern

    o Use the Proxy pattern when:

    o You wish to wrap an object in anotherobject that performs some additionaltasks

    o e.g. loading the data for an object from diskwhen it is first needed

    o e.g. recording the usage of an object'smethods

    o etc.

    B h i l D i P tt

  • 7/31/2019 g of Design Patterns

    40/54

    Behavioural Design Patterns

    o There are many design patterns that

    relate to the communication between(or dynamic relationships between)objects

    o In this class, we will focus on three

    important patterns:o Iterator

    o Observer

    o Template Method

    The Iterator Pattern

  • 7/31/2019 g of Design Patterns

    41/54

    The Iterator Pattern

    o The Idea: To provide means of

    accessing elements of an aggregatein a sequential manner

    o An Iterator sequentially processes eachelement of an aggregate

    o e.g. An Iterator might be used to search aLinkedList for a specific element

    Iterator: Example

  • 7/31/2019 g of Design Patterns

    42/54

    Iterator: ExampleIterator{abstract}

    First() : ItemNext() : ItemMoreElements() : Bool

    LinkedListIteratorArrayIterator

    First() : ItemNext() : Item

    MoreElements() : Bool

    First() : ItemNext() : Item

    MoreElements() : Bool

    Array LinkedListItem

    Iterator: Example

  • 7/31/2019 g of Design Patterns

    43/54

    Iterator: Examplepublic class ArrayIterator implements Iterator {

    private String[] data;private int index;

    public ArrayIterator(String[] data) {this.data = data;this.index = 0;

    }public String first() {

    index = 0;return data[0];

    }public String next() {

    index++;return data[index];

    }public boolean moreElements() {

    if (index >= data.length)

    return false;return true;

    }}

    Iterator: Example

  • 7/31/2019 g of Design Patterns

    44/54

    Iterator: Examplepublic class LinkedListIterator implements Iterator {

    private LinkedListElement first;private LinkedListElement current;

    public LinkedListIterator (LinkedListElement first) {this.first = first;this.current = first;

    }public String first() {

    return first.value();}public String next() {

    current = current.getNext();return current.value();

    }public boolean moreElements() {

    if (current.getNext() == null)return false;

    return true;}

    }

    The Iterator Pattern

  • 7/31/2019 g of Design Patterns

    45/54

    The Iterator Pattern

    o Use the Iterator pattern when:

    o To access an aggregate's contentssequentially, in a manner that isindependent of the implementation ofthe aggregate

    o i.e. To provide polymorphic iteration

    The Observer Pattern

  • 7/31/2019 g of Design Patterns

    46/54

    The Observer Patterno The Idea: To provide a means for objects

    (Observers) to notify other objects

    (Observables) that they wish to be notifiedof changes to their state

    o e.g. In the MVC architecture, the View couldregister itself as an observer of the Model

    o Thus, changes to the model would trigger eventsto be sent to the View, telling it to update its stateto reflect the changes

    Observer: Example

  • 7/31/2019 g of Design Patterns

    47/54

    Observer: Example

    MyBugObserver

    BugObserver{abstract}

    BugAdded()

    BugStatusChanged()

    ObservableBugListImpl

    bugs: List

    ObservableBugList{abstract}

    AddObserver()

    RemoveObserver()

    observers

    BugAdded()BugStatusChanged()

    AddObserver()

    RemoveObserver()

    Observer: Example

  • 7/31/2019 g of Design Patterns

    48/54

    Observer: Examplepublic abstract class ObservableBugList {

    private ArrayList observers;public void addObserver(BugObserver observer) {

    observers.add(observer);}public void removeObserver(BugObserver observer) {

    observers.remove(observer);}

    public abstract notifyBugAdded(Bug bug);public abstract notifyBugStatusChanged(Bug bug);}

    public MyBugObserver implements BugObserver {public void bugAdded(BugAddedEvent event) {

    }public void bugStatusChanged(BugStatusChangedEvent e) {

    }

    }

    The Observer Pattern

  • 7/31/2019 g of Design Patterns

    49/54

    The Observer Patterno Use the Observer pattern when:

    o A change to an object should cause otherobjects to be notified of the change

    o The Observers may require notification so they canrecord the changes, update their own stateaccordingly, etc.

    o These objects (Observers) may change over time

    o The object being watched (observable) does notnecessarily need to know about the objectsobserving it

    Template Method Pattern

  • 7/31/2019 g of Design Patterns

    50/54

    Template Method Patterno The Idea: Provide means to customize

    behaviour through subclasses

    o The Template class will describe the mainalgorithms, but will leave various methodsabstract to handle some small portion of thebehaviour

    o Each subclass will handle this small portiondifferently, depending upon the desired outcome

    Template Method Pattern

  • 7/31/2019 g of Design Patterns

    51/54

    Template Method Patterno e.g. Consider a Parser that checks an HTML

    fileo The Parser could be developed using a Template

    class, which would handle the generic parsing

    o Subclasses could define some methods to handleevents that occur during the parsing process:

    o startBlockElement(), endBlockElement(),

    startCharacterElement(), endCharacterElement(),startDocument(), endDocument()

    o A program that turns HTML files into a tree datastructure might do one thing in these methods,whereas a browser (which draws the HTMLelements as its reads the file) might do something

    different

    Template Method: Example

  • 7/31/2019 g of Design Patterns

    52/54

    Template Method: Example

    XMLParserTemplate{abstract}

    ParseXMLFile(filename: String)

    processStartTag(tagName: String)

    processArgument(tagName: String,

    argumentName: String,

    argumentValue: String)processBody(tagName: String,

    bodyText: String

    processEndTag(tagName: String)

    ConvertHTMLToText

    processStartTag(tagName: String)processArgument(tagName: String,

    argumentName: String,

    argumentValue: String)

    processBody(tagName: String,

    bodyText: String

    processEndTag(tagName: String)

    Template Method: Example

  • 7/31/2019 g of Design Patterns

    53/54

    Template Method: Examplepublic class ConvertHTMLToText extends XMLParserTemplate {

    private FileWriter out;

    public void convert(String htmlFile, String textFile) {out = new FileWriter(textFile);

    parseXMLFile(htmlFile);

    out.close();

    }

    public void processStartTag(String tagName) {}

    public void processArgument(String tagName,String argumentName, String argumentValue) {}

    public void processBody(String tagName, String bodyText) {

    out.write(bodyText);

    }

    public void processEndTag(String tagName) {}

    }

    The Template Pattern

  • 7/31/2019 g of Design Patterns

    54/54

    The Template Patterno Use the Template pattern when:

    o An base algorithm is identical between all types

    of an objecto The difference between each type are small, such

    as how they handle the occurrence of variousevents

    o Implement the abstract methods to define the

    specific behaviouro The template class will invoke these methods at

    the correct time during execution of the algorithm