CS3342 Lecture 8

Software Design Patterns - State Pattern, Singleton Pattern, Factory Method Pattern, Facade Pattern

Benefits of Design Patterns 

Design patterns enable large-scale reuse of software architectures and also help document systems
Patterns explicitly capture expert knowledge and design tradeoffs and make it more widely available
Patterns help improve developer communication
Pattern names form a common vocabulary (Jargon)

Creational Patterns: a Catalog

Purpose: Deals with initialization of objects and selection among classes

Abstract Factory: Factory for building related objects
Builder: Factory for building complex objects incrementally
Factory Method: Method in a derived class creates associates
Prototype: Factory for cloning new instances from a prototype
Singleton: Factory for a singular (sole) instance. 

Structural Patterns: a Catalog 

Purpose: Describe ways to construct and compose objects to realize new functionality

Adapter: Translator adapts a server interface for a client
Bridge: Abstraction for binding one of many implementations
Composite: Structure for building recursive aggregations
Decorator: Decorator extends an object transparently
Facade: Simplifies the interface for a subsystem
Flyweight: Many fine-grained objects shared efficiently.
Proxy: One object approximates another

Behavioral Patterns: a Catalog

Purpose: Distribute the responsibility among objects and define the protocol for object and class interactions.

Chain of Responsibility: Request delegated to the responsible service provider
Command: Request or Action is first-class object, hence re-storable
Iterator: Aggregate and access elements sequentially
Interpreter: Language interpreter for a small grammar
Mediator: Coordinates interactions between its associates
Memento: Snapshot captures and restores object states privately
Observer: Dependents update automatically when subject changes
State: Object whose behavior depends on its state
Strategy: Abstraction for selecting one of many algorithms
Template Method: Algorithm with some steps supplied by a derived class
Visitor: Operations applied to elements of a heterogeneous object structure


Design Pattern: State and Strategy 

Intend
  • Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Motivation
  • An object’s behavior depends on its state
  • According to different classifications at run-time
  • Ability to change to another state with ease
Example – Membership Classification
  • Provides different behaviors/actions for different members
  • Customers can be treated differently due to memberships
  • Customers can be easily changed to another membership
State Interface
  • Implemented by concrete classes
  • Different Handle() functions
Context Class
  • Maintains a State
  • Aggregation link
  • Different Request() functions
  • state.handle()
  • Implemented by different ConcreteState
  • state object can be changed.
Example1 - Membership State:
Loyalty Customer has 3 Membership Types
Green (New Customer) - No discount (pays 100%) - Deposit (needs to pay 100% upfront)
Silver (After spending >$5,000, upgraded) - 20% discounts (pays 80%) - Deposit (only need to pay 50% upfront)
Gold (After spending >$10,000, upgraded) - 50% discounts (pays 50%) - Deposit (do not need to pay, 0% upfront)

 =>  => 

 => 

Example 2 – Library Members:

Members pay for a penalty for late-returns
  • Senior, Adult, Child
Problem
  • A Child will grow up
  • A Adult will grow old
  • Needs to change membership

Solution:

Summary:

  Benefits
  • Consolidate
    • Puts all behavior associated with a state into 1 object
  • Consistent
    • Allows state transition logic into a state rather than many if/then switch statements for different logics
  • Allows state changes
    • Avoids inconsistent states changes to occur and complexity involved
  Drawback
  • The number of objects increased.
  • Might need to use with Singleton pattern to save the number of objects being created

Design Pattern: Strategy 

(Similar to State Pattern, but it has only 1 function in each state.)

Intend
  • Define a family of algorithms, encapsulate each one, and make them interchangeable.
  • Provides more independence for clients to use it.
Motivation
  • An object’s behavior depends on its choice
  • Need different variants of an algorithm
  • Difference to State Pattern
  • Only 1 function in State

Example:

A class wants to decide at run-time what algorithm it should use to sort an array. Many different sort algorithms are readily available.
Encapsulate different sorting algorithms using the Strategy pattern.
Strategy has 1 (one) function in each state, sort(). 
 
State vs Strategy Pattern
Task Handling
  • Strategy Pattern handles a single and specific task (sort ())
  • State Pattern handles many tasks (discount(), deposit()..etc)
Object Handling
  • Strategies are passed to the context object (e.g..to SortArray as parameters)
  • States are created by the context object
Client Perspective
  • Both solutions are very similar.


Design Pattern: Singleton

Motivation/when to use
  • Need to have ONLY one(1) instance for a class.
  • Singleton instantiates itself, and only one(1) of such.
Intent
  • Ensure that only 1 object instance is ever created.
  • Provide a global point of access.
  • Save the number of duplicated objects being created. Such as in State Pattern.
Implementation
  • Variable instance (refers to itself, initialized before constructor is called).
  • Constructor > private(-) Constructor (non-accessible)
  • Method > getInstance() (returns the single instance)

class Singleton {
    public: 
        static Singleton* getInstance(); 
    protected: 
        Singleton(); 
        Singleton(const Singleton&); 
        Singleton& operator = (const Singleton&); 
    private:
        static Singleton* instance; 
}; 
Singleton *p2 = Singleton::getInstance(); 
Caller/Client Usage:
  • Singleton.getInstance().method_x();
  • Ensure that only one(1) instance is created.
  • Constructor is private, not accessible.
  • Only way of instantiating the class is through the method getInstance();
  • Provides a global point of access. 

Example - President:

President Case study – Using Singleton Design Pattern
  • To enforce that: There is Only 1 President at any time.
  • There are many (n) Ministers need to contact the president.
Pointing to one (1), single object:
  • President p1 = President.getInstance ();   //refer to the same object
  • President p2 = President.getInstance ();   //refer to the same object

To validate that it only produce 1 single object
Design:
  • We have 1 president and many Minsters calling this 1 president object.
  • Use a counter to keep track how many the “same” one object being called.
Result: 

Singleton vs Non_Singleton:

Summary:

  • Used  to ensure that a class has only one instance. For example, one printer spooler object, one file system, one window manager, etc.
  • One may use a global variable to access an object but it does not prevent one from creating more than one instance, Singleton prevents creating more than 1 object instance.
  • Instead the class itself is made responsible for keeping track of its instance. It can thus ensure that no more than one instance is created. This is the singleton pattern.


Design Pattern: Factory Method

Motivation/when to use
  • Also known as “Virtual Constructor”
  • Defines an interface for creating an object
  • Leaves the “choice” of its type to the subclasses
  • Creation of object to be determined at run-time.
Intent
  • Defines an interface for creating object
  • Let subclasses to decide which class to create.
  • Provides the newly created object through a common interface
Implementation
  • Product (interface) ConcreteProduct implements the Product interface
  • Factory creates/generate Product object via factoryMethod()
  • ConcreteFactory implements and produces ConcreteProduct object.

Example - Document Application:
  • Document class that needs to be created is specific to the application at run-time by user. So it doesn’t know which class to use in advance.
  • Factory Method design pattern solves this problem

Participants and Communication

•Product (Document): Defines the interface of objects the factory method creates.
•ConcreteProduct (MyDocument, HtmlDocument, PdfDocument): Implements the Product interface.
•Creator (Application): Declares factory method which returns an object of type Product(Document). Also, may define the factory method to create a Product(Document) object.
•ConcreteCreator (DocumentFactory): Extends and overrides the factory method to return an object instance of ConcreteProduct (MyDocument, HtmlDocument, PdfDocument) upon request.
 

Summary:

The solution uses Factory Method Pattern
  • To generate required object based upon request
Allows objects to be dynamically created at runtime
  • Subject to user’s inputs etc.
Factory Method Pattern
  • One of the most commonly used Design Patterns in SE
  • Provides an mechanism to produce different objects.


Design Pattern: Façade

Façade is generally means (in Architecture)
  • Exterior (outside part) of a building
  • Usually the front
  • French, literately meaning “frontage” or “face”  
A façade is an object provides
  • A simplified interface (front-end) to other code.
  • Such as a class library.
  • Reduce dependencies of outside code base
Intent
  • Provides a more simplified interface to access complex backend classes.
  • Hiding the backend

 Structure

 

 

 

posted @ 2018-03-26 19:10  Charonnnnn  阅读(361)  评论(0编辑  收藏  举报