design-patterns by AshishSaxena10

VIEWS: 9 PAGES: 41

									                          Design Patterns
                   CS 406 Software Engineering I
                                       Fall 2001


                                 Aditya P. Mathur


                                Purdue University




October 30, 2001
                        Organization
Patterns:

 Behavioral:
   Observer

 Structural:
    Façade

 Creational
    Abstract Factory
    Factory Method
    Singleton

 Excellent reference:

 Design Patterns book by Erich Gamma, et al., Addison-Wesley, 1994.



                                    Design Patterns                   2
            Design Patterns [1]
• A solution to a problem that occurs repeatedly in a
  variety of contexts.


• Each pattern has a name.



• Use of each pattern has consequences.




                         Design Patterns                3
        Design Patterns [2]

• Generally at a “higher level” of abstraction.



• Not about designs such as linked lists or hash tables.



• Generally descriptions of communicating objects and
  classes.



                      Design Patterns                  4
         Observer Pattern [1]
• Need to separate presentational aspects with the data,
  i.e. separate views and data.
• Classes defining application data and presentation can
  be reused.

• Change in one view automatically reflected in other
  views. Also, change in the application data is reflected in
  all views.

• Defines one-to-many dependency amongst objects so
  that when one object changes its state, all its
  dependents are notified.
                       Design Patterns                    5
                Observer Pattern [2]

                              Relative Percentages
         A B C D
                                                                    A
X       15 35 35 15                                            D
Y       10 40 30 20                                                     B
                                                                C
Z       10 40 30 20
                                 A      B    C       D


                                  A=10%
                                  B=40%
                                  C=30%                  Application data
    Change notification
                                  D=20%
    Requests, modifications
                                  Design Patterns                           6
      Observer Pattern [3]
                    observers
 Subject                                        Observer

attach (Observer)                               Update()
detach (Observer)
                    For all x in observers{
Notify ()             x  Update(); }

                                                Concrete Observer
                                      subject
Concrete Subject                                Update()

 GetState()                                     observerState
 SetState()
                                                observerState=
 subjectState                                    subject  getState();
                         Design Patterns                             7
Class collaboration in Observer

:ConcreteSubject      :ConcreteObserver-1            :ConcreteObserver-2


                SetState()
     Notify()

     Update()

                GetState()

     Update()

                                               GetState()

                             Design Patterns                               8
Observer Pattern: Observer code
class Subject;


class observer {               Abstract class defining
public:                        the Observer interface.
         virtual ~observer;

         virtual void Update (Subject* theChangedSubject)=0;

protected:

         observer ();

};
                                        Note the support for multiple subjects.

                                  Design Patterns                                 9
Observer Pattern: Subject Code [1]
      class Subject {
                                            Abstract class defining
      public:
                                            the Subject interface.
                 virtual ~Subject;

                 virtual void Attach (observer*);
                 virtual void Detach (observer*) ;
                 virtual void Notify();

      protected:
                 Subject ();

      private:
                 List <Observer*> *_observers;
      };
                          Design Patterns                             10
Observer Pattern: A Concrete Observer [1]

     class DigitalClock: public Widget, public Observer {
     public:
         DigitalClock(ClockTimer*);
         virtual ~DigitalClock();
                                                   Override Observer operation.
         virtual void Update(Subject*);
         virtual void Draw();
                                                  Override Widget operation.
     private:
         ClockTimer* _subject;

         }



                                Design Patterns                                11
When to use the Observer Pattern?

• When an abstraction has two aspects: one dependent
  on the other. Encapsulating these aspects in separate
  objects allows one to vary and reuse them
  independently.

• When a change to one object requires changing others
  and the number of objects to be changed is not known.

• When an object should be able to notify others without
  knowing who they are. Avoid tight coupling between
  objects.

                       Design Patterns                     12
Observer Pattern: Consequences

• Abstract coupling between subject and observer.
  Subject has no knowledge of concrete observer classes.
  (What design principle is used?)

• Support for broadcast communication. A subject need
  not specify the receivers; all interested objects receive
  the notification.
• Unexpected updates: Observers need not be concerned
  about when then updates are to occur. They are not
  concerned about each other’s presence. In some cases
  this may lead to unwanted updates.
                         Design Patterns                      13
Facade Pattern: Problem

                                  Client Classes



                             Need to communicate
                             with




                           Subsystem classes




         Design Patterns                   14
Facade Pattern: Solution

                                  Client Classes




        Facade




                           Subsystem classes


         Design Patterns                   15
 Facade Pattern: Why and What?
• Subsystems often get complex as they evolve.

• Need to provide a simple interface to many, often small,
  classes. But not necessarily to ALL classes of the
  subsystem.
• Façade provides a simple default view good enough for
  most clients.
• Facade decouples a subsystem from its clients.

• A façade can be a single entry point to each subsystem
  level. This allows layering.
                        Design Patterns                 16
Facade Pattern: Participants and Communication

• Participants: Façade and subsystem classes

• Clients communicate with subsystem classes by
  sending requests to façade.

• Façade forwards requests to the appropriate subsystem
  classes.
• Clients do not have direct access to subsystem classes.




                        Design Patterns                 17
               Facade Pattern: Benefits


• Shields clients from subsystem classes; reduces
  the number of objects that clients deal with.


• Promotes weak coupling between subsystem and its
  clients.


• Helps in layering the system. Helps eliminate circular
  dependencies.



                         Design Patterns                   18
             Example: A compiler
                             Compiler                           Invocations
                              Compile()
        Stream
                                      Scanner       Token
    BytecodeStream
                                      Parser        Symbol
     CodeGenerator
                                     PnodeBuilder           Pnode



                                       StatementNode         ExpressionNode

RISCCodegenerator    StackMachineCodegenerator



                             Design Patterns                              19
      Façade Pattern: Code [1]
class Scanner { // Takes a stream of characters and produces a stream of tokens.


      public:
                  Scanner (istream&);

                  virtual Scanner();

                  virtual Token& Scan();

       Private:

                    istream& _inputStream;

       };



                                       Design Patterns                     20
      Façade Pattern: Code [2]
class parser { // Builds a parse tree from tokens using the PNodeBuilder.

      public:
                Parser ();

                virtual ~Parser()

                virtual void Parse (Scanner&, PNodeBuilder&);


       };




                                    Design Patterns                         21
       Façade Pattern: Code [3]
class Pnodebuilder {                 // Builds a parse tree incrementally. Parse tree
                                     // consists of Pnode objects.
  public:
            Pnodebuilder ();

            virtual Pnode* NewVariable (         // Node for a variable.

                       Char* variableName
            ) const;

            virtual Pnode* NewAssignment (
                                                                // Node for an assignment.
                       Pnode* variable, Pnode* expression
            ) const;
 Private:                                               // Similarly...more nodes.

            Pnode* _node;
 };                                   Design Patterns                                 22
        Façade Pattern: Code [4]
class Pnode {      // An interface to manipulate the program node and its children.

 public:
   // Manipulate program node.

         virtual void GetSourcePosition (int& line, int& index);

      // Manipulate child node.
         virtual void Add (Pnode*);
         virtual void Remove (Pnode*);
       // ….
         virtual void traverse (Codegenerator&);        // Traverse tree to generate code.
 protected:
       PNode();
 };
                                      Design Patterns                                  23
      Façade Pattern: Code [7]
class Compiler {         // Façade. Offers a simple interface to compile and
 public:                 // Generate code.
                                                Could also take a CodeGenerator
         Compiler();                            Parameter for increased generality.
         virtual void Compile (istream&, BytecodeStream&);
     }
void Compiler:: Compile (istream& input, BytecodeStream& output) {
         Scanner scanner (input);
         PnodeBuilder builder;
         Parser parser;
         parser.Parse (scanner, builder);
         RISCCodeGenerator generator (output);
         Pnode* parseTree = builder.GetRootNode();
         parseTreeTraverse (generator);
  }                              Design Patterns                            24
Abstract Factory: The Problem
1. Consider a user interface toolkit to support multiple look-
   and-feel standards.

2. For portability an application must not hard code its widgets
   for one look and feel.



       How to design the application so that incorporating new look
       and feel requirements will be easy?




                            Design Patterns                        25
Abstract Factory Pattern: Solution[1]

  1.   Define an abstract WidgetFactory class.

  2.   This class declares an interface to create different kinds
       of widgets.

  3.   There is one abstract class for each kind of widget and
       concrete subclasses implement widgets for different
       standards.

  4.   WidgetFactory offers an operation to return a new widget
       object for each abstract widget class. Clients call these
       operations to obtain instances of widgets without being
       aware of the concrete classes they use.
                        Design Patterns                             26
        Abstract Factory: Solution[2]
         WidgetFactory                                                Client
       CreateScrollbar()                            Window
       CreateWindow()

                                     MacWindow                 WWindow



                                                          ScrollBar
 WWidgetFactory



           MacWidgetFactory
                                                MacScrollBar      WScrollBar


One for each standard.        Design Patterns                              27
       Abstract Factory: Solution[2]
      AbstractFactory                                                    Client
      CreateScrollbar()                          AbstractProductA
      CreateWindow()

                                    ProductA2                ProductA1



                                                      AbstractProductB
ConcreteFactory1


          ConcreteFactory2

                                               ProductB2            ProductB1
          CreateProductA()
          CreateProductB()
                             Design Patterns                                    28
     Abstract Factory Pattern: Participants and
                  Communication

• AbstractFactory: Declares the interface for operations to
  create abstract product objects

• ConcreteFactory: Implements the operations to create concrete
  product objects.

• AbstractProduct: Declares an interface for a type of product object.

• ConcreteProduct: Defines a product object to be created by the
  corresponding factory.

• Client: Uses only the interface declared by the abstractFactory and
  AbstractProduct classes.
                             Design Patterns                        29
Abstract Factory Pattern: Code [1]
class MazeFactory {                    // Creates components of mazes.
                                       // Builds rooms, walls, and doors.
     public:
               MazeFactory();

               virtual Maze* MakeMaze() const

                       { return new Maze;}           // This factory is a collection of
                                                     // factory methods. Also, this class
               virtual Wall* MakeWall() const        // acts both as Abstract and Concrete
                                                     // Factory
                       { return new Wall;}


               virtual Wall* MakeRoom(int n) const

                       { return new Room;}
        // more methods.
 }                                       Design Patterns                              30
Abstract Factory Pattern: Code [1]
Maze* MazeGame:: CreateMaze (MazeFactory& factory)
                                                          // Builds a maze.

         Maze* aMaze = factory.MakeMaze();

         Room* myroom = factory.MakeRoom(1);

         Room* herroom = factory.MakeRoom(2);

         Door* aDoor = factory.MakeDoor(myRoom,herRoom)

         aMaze AddRoom(myRoom)                     // One can also create a
                                                    // BombedMazeFactory with
         aMaze AddRoom(herRoom)                    // different types of Rooms
                                                    // and Walls.
     // More code to add walls.

 }                                Design Patterns                             31
Factory Method: The Problem [1]

1. Frameworks use abstract classes to define and maintain
   relationships between objects

2. Consider a framework for applications that present multiple
   documents to the user. A drawing application is an example.

3. This framework defines two abstract classes: application and
   document. These ought to be sub classed by clients for
   application specific implementation.

4. The application class will create and manage documents
   when required, e.g. when a New command is selected from
   the menu.

                          Design Patterns                         32
    Factory Method Pattern: The
            Problem [2]
5. Document sub class is application specific. Hence the
   Application class does not know what kind of document to
   create!


6. Problem: The framework must instantiate classes but it only
   knows about the abstract classes, which it cannot initiate!




                           Design Patterns                       33
Factory Method Pattern: Solution[1]

    1.   The Factory Method pattern encapsulates the knowledge
         of which Document subclass to create and moves this
         knowledge out of the framework.

    2.   Application subclasses redefine an abstract CreateDoc()
         method to return the appropriate Document subclass.

    3.   When an Application is instantiated, it can instantiate
         application specific Documents without knowing their
         class.




                         Design Patterns                           34
Factory Method: Solution[2]
                                                          Factory method
                                     docs
 Document                                   Application
               *                        1
Open()                                      CreateDoc()
Close()                                     NewDoc()
                                            OpenDoc()
Save()


                                            MyApplication

  MyDocument                                CreateDoc()

                                 Document* doc=CreateDoc();
                                 docs.Add(doc);
                                 docOpen();
                   Design Patterns                                  35
Factory Method Pattern: Structure

   Product                                 Creator

                                           FactoryMethod()
                                           SomeOperation()

             product=Factory method

                                           ConcreteCreator

ConcreteProduct                             FactoryMethod()


                                Return new ConcreteProduct

                      Design Patterns                         36
      Factory Method Pattern: Participants and
                  Communication

• Product (Document): Defines the interface of objects the
  factory method creates.


• ConcreteProduct (MyDocument): Implements the Product interface.


• Creator (Application): Declares factory method which returns an
  object of type Product. Also, may define the factory method to
  create a Product object.


• ConcreteCreator (MyApplication): Overrides the factory method to
  return an instance of a ConcreteProduct.
                             Design Patterns                         37
                  Other Patterns: Singleton


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

• 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 Patterns                             38
        Singleton Structure

     Singleton

static uniqueInstance             return uniqueinstance
singletonData

static Instance()
SingletonOp()
GetSingletonData()




                        Design Patterns                   39
            Singleton Code [1]
class Singleton {             // Only one instance can ever be created.

  public:
             static Singleton* Instance();

  protected:
                                     // Creation hidden inside Instance().
             Singleton();


  private:
             Static Singleton* _instance


  }                                     // Cannot access directly.
                            Design Patterns                                  40
        Singleton Code [2]
Singleton* Singleton::_instance=0;


Singleton* Singleton:: Instance(){

  if (_instance ==0) {
        _instance=new Singleton;
  }
Return _instance;
                        // Clients access the singleton
}
                        // exclusively via the Instance member
                        // function.


                     Design Patterns                             41

								
To top