Docstoc

Structural Design Patterns

Document Sample
Structural Design Patterns Powered By Docstoc
					Structural Design Patterns

Yaodong Bi
September 2, 2012
Structural design patterns

   Façade
   Decorator
   Composite
   Proxy
   Adapter
   Bridge
   Flyweight
Façade

   Design Purpose
    – Provide a single and simple interface to a
      package of classes
   Design Pattern Summary
    – Define a single and simple interface for
      clients to use the functionality of the
      package
Façade - examples

   A compiler package
    – It normally contains many
      classes/subpackages like Scanner, Parser,
      etc.
    – Most clients only want to compile their
      programs, i.e., they don’t care about
      functions of individual components in the
      package
    – Use Façade to provide a simple default
      interface to most clients.
Façade - Structure



     Client
Use op1(), op2(),
op3(), and op4()
                                   Facade
                                op1()
                                op2()
                                op3()
                                op4()


                       ClassA                   ClassC
                    op3_a()                  op4_c()


                                    ClassB
                                 op1_b()
                                 op2_b()
Sequence Diagram


 Client       Facade        B:ClassB   A:ClassA   C:ClassC


     op1()       op1_b()


      op3()       op3_a()

      op4()       op4_c()

     op2()       op2_b()
Façade - Structure

         Client
Compiler.compile(“test.c”)




                                                  Compiler
                                               compile()




                             ProgramNodeBuilder              Scanner




                               CodeGenerator                 Parser
    Façade – Sample code
Class Scanner {
     public Scanner(InputStream sourcecode)            Class Compiler {
     public Token scan() { … }                           public void compile(InputStream sc,
}
Class Parser {                                                  OutputStream bytecode) {
     public parse(Scanner s, ProgramNodeBudiler p) {       Scanner sc = new Scanner(sc);
     …}                                                    ProgramNodeBuilder pnb = new
}                                                                 ProgramNodeBuilder();
Class ProgramNodeBuilder {
     public ProgramNode newVariable(…) { … }               Parser parser = new Parser();
     public ProgramNode newAssignment(…) { … }             parser.parse(sc, pnb);
     public ProgramNode newReturnStmt(…) { … }             IntelCodeGenerator cg = new
}
Class CodeGenerator {                                             IntelCodeGenerator(bytecode)
     public void visitStatementNode(…) { … }               ProgramNode nodetree =
     public void visitExpressionNode(…) { … }               pnb.getRootNode();
}
                                                           parsetree.traverse(cg);
                                                       }
 Façade - Examples

         framework

           AccountException      Customer                      Account
                                 getCustomerName()             getAccountNum()
                                 getNumAccounts()              deposit( int )
          CustomerException      getPersonalNote()             getBalance()
                                 getAccount( int )



            BankCustomers
                                                        1..n
                                  BankCustomer                   BankAccount
Client

              BankCustomers
              doDeposit( int amt, Customer cust, Account acc )
              getBankAccount( Customer cust, int accNum )
              getBankCustomer( String custName )
Façade - comments

   Façade can reduce the degree of
    dependency between packages
    – Packages are dependent on each other only
      through their facades, not individual classes
   Use Façade to provide a simple default view
    of the package that is enough for most
    clients
   Façade does not try to encapsulate/hide the
    components in the package since there may
    be clients who need to access individual
    components in the package
Decorator

   Design Purpose
    – Add responsibilities to an object at
      runtime.
   Design Pattern Summary
    – Provide for a linked list of objects, each
      encapsulating responsibility.
Decorator - examples

   The word processor example
    – A text view may have a border and a
      scroll bar and maybe other bells and
      whistles attached to it
    – How can those bells and whistles be
      added to the text view?
    – Inheritance?
Decorator – structure

                         Component
                       operation()
                       add(Component)
Client                 remove(Component)
                       getChild()




         ConcreteComp               Decorator
         operation()               Operation()       comp




                 void operation()
                 {
                    // do actions of the decorator
                    comp.operation();
                    // do actions of the decorator
                 }
Decorator - example
Decorator – structure

                    VisualComponent
                    draw()

Client

            TextView              Decorator
           draw()                draw()
                                                   comp
                                                       comp.draw()



                    ScrollDecorator            BorderDescrotor
                draw()                        draw()
                scrollTo()                    drawBorder()
                scrollPosition                borderWidth




                                 super.draw()
                                 this.drawBorder()
Decorator – examples


  Client




             :Decorator1



             :Decorator2

           :ConcreteComp
Decorator - Sequence Diagram


 Client             Component           :Decorator1        :Decorator2       :ConcreteComp




      operation()         operation()
                                                 operation()
                                                                   operation()



                                                                    return
                                                  return
          return              return
Decorator – examples


                         :Reader


                                                            1
 :InputStreamReader                : BufferedStreamReader




 System.in:InputStream
Decorator – examples


 : BufferedStreamReader




                  :InputStreamReader




                                       System.in:InputStream
Decorator – key concept

   allows addition to and removal from
    objects at runtime
  Decorator – sample code
class VisualComponent {                      Class Window {
   virtual void Draw();                         void SetContents (VisualComponent*
   virtual void Resize();                        contents) {
};                                              // ...
class Decorator : public VisualComponent {   }
   Decorator(VisualComponent*);
   void Decorator::Draw () {                 Window* window = new Window();
      _component->Draw();                    TextView* textView = new TextView;
   }
   VisualComponent* _component;              window->SetContents(textView);
};
class BorderDecorator : public Decorator {   window->SetContents(
   BorderDecorator(VisualComponent*, int        new BorderDecorator(
    borderWidth);                                  new ScrollDecorator(textView), 1
   void Draw(){                                 )
      Decorator::Draw();
                                             );
      DrawBorder(_width);                    Window.draw();
   }
   private void DrawBorder(int);
   private int _width;
};
Composite

   Design Purpose
    – Represent a Tree of Objects
   Design Pattern Summary
    – Use a Recursive Form in which the tree
      class aggregates and inherits from the
      base class for the objects.
 Composite - structure


          Objects                Classes
                                                 1..n
                                  Component
non-leaf node

                            “every              “non-leaf nodes
                            object             have one or more
                            involved              components”
                            is a
                            Component
                            object”
                leaf node
                                 NonLeafNode
Composite - structure


                      Component           1..n
Client               add( Component )
                    Remove(component)
                           doIt()



                                        comp

         LeafNode    NonLeafNode
           doIt()       doIt()                   for all elements e in comp
                                                     e.doIt()


         TypeANonLeafNode     TypeBNonLeafNode
               doIt()               doIt()
Composite – A Class Diagram


 :Client                      N0:NonLeafNode




                  N1:NonLeafNode           N2:NonLeafNode




                             L2:LeafNode           L3:LeafNode
           L1:LeafNode
Composite – sequence diagram


:Client        N0:NonLeafNode    N1:NonLeafNode         L1:LeafNode
                                                             L2:LeafNode
                                           N2:NonLeafNode           L3:LeafNode
      doIt()
                        doIt()        doIt()

                                      doIt()

                        doIt()
                                                     doIt()
Composite – examples


                        Component
                                    1..n
Composite in java.awt


                        Container
                                     component


      Window             Canvas        …..
Proxy

   Design Purpose
    – Avoid the unnecessary execution of
      expensive functionality in a manner
      transparent to clients.
   Design Pattern Summary
    – Interpose a substitute class which
      accesses the expensive functionality only
      when required.
Proxy – examples

                        Instantiate with
                                                        BaseActiveClass
                        Proxy object
Client                                                  expensiveMethod()
                                                         anotherMethod()




          RealActiveClass                                     Proxy
         expensiveMethod()                              expensiveMethod()
          anotherMethod()                                anotherMethod()


                       if ( realActiveObject == null )    // not loaded yet
                       { realActiveObject = getRealActiveObject();
                             realActiveObject.expensiveMethod();
                       }
                       else { realActiveObject.expensiveMethod(); }
Proxy – sequence diagram

Client              BaseActiveClass   Proxy                RealActiveClass


         expensiveMethod()
                                               create() if needed




                                              expensiveMethod()
Proxy – examples

                        Instantiate with
TexDoc                  Proxy object                Graphics
graphics                                             Display()




           Image                           image   ImageProxy
           display()                                display()
           bitmap                                   fileName


                       if ( image == null ) {     // not loaded yet
                             image = new Image(fileName);
                       }
                       Image.display();
   Proxy – Sample code

Class TextDoc {
    graphics g;                             Interface Graphics {
    TextDoc(ImageProxy ip) {                     display();
              g = ip;                       }
    }                                       Class Image Implements Graphics {
    void display() {                             Bitmap bitmap;
              g.display();                       Image(FileName fn) {
    }                                                    bitmap = readImage(fn);
}                                                }
Class ImageProxy implements Graphics {           display() {
    FileName fileName;                                   // draw the bitmap
    Image image;                                 }
    ImageProxy(FileName fn) {                    readImage(FileName fn) {
              fileName = fn;                             // read from the file(fn)
    }                                                    // create a bitmap
    display() {                                  }
       if (image == null)                   }
             image = new Image(fileName);
       image.display();
    }
}
Adapter

   Design Purpose
    – Allow an application to use external
      functionality in a retargetable manner.
   Design Pattern Summary
    – Write the application against an abstract
      version of the external class; introduce a
      subclass that aggregate the external
      class.
Adapter - examples

   Interact with legacy systems
    – When you design a new system which has to
      interact with a legacy system, you may not want
      to the new system tightly coupled with (or
      dependent upon) the legacy system since the
      legacy system may be replaced in the future.
   Using 3rd party systems
    – You may want to be able to easily substitute the
      current 3rd party system with another one.
Class Adapter
Object Adapter - Structure



  Client          Target                              Adaptee
            +request()                            +requestedMethod();



                                        adaptee
                 Adapter
            +request()




            adaptee.requestedMethod()
Adapter – sequence diagram


Client                      Target                      Adapter                                  Adaptee

    request(TargetIn):TargetOut   request(TargetIn):TargetOut   convert(TargetIn):AdapteeIn




                                                                requestedMethod(AdapteeIn):AdapteeOut




             Return TargetOut       Return TargetOut             convert(AdapteeOut):TargetOut
Object Adapter – sample code

Interface Target {                      Class Adapter implements Target {
  public TargetOut request(TargetIn);     private Adaptee adaptee;
}                                         public Adapter(Adaptee ad) {
                                            adaptee = ad;
Class Adaptee {                           }
  …                                       public TargetOut request(TargetIn ti) {
  public AdapteeOut                         AdapteeIn ai = convert(ti);
          requestedMethod(AdapteeIn)        AdapteeOut ao =
  {                                              adaptee.requestedMethod(ai);
     // produce AdapteeOut;                 return convert(ao);
     return AdapteeOut;                   }
  }                                       private AdapteeIn convert(TargetIn ti)
  …                                       {
}                                           // convert TargetIn to AdapteeIn
                                          }
                                          private TargetOut convert(AdapteeOut ao)
                                          {
                                            // convert AdapteeOut to TargetOut
                                          }
                                        }
Object Adapter - Example


                    Shape
DrawingTool   +boundingBox()                       TextView
              +createManipulator()             +getExtent();



                                      text
                 TextShape
              +boundingBox()
              +createManipulator()

                                                text.getExtent()


                                     return new TextManipulator()
Design for Adaption

   Pluggable Adapters
    – A small set of operations is specified for
      adapter & adaptee to implement
    – Using Abstract Operations
        Client and target are the same entity
        Adapter overrides abstract operations to
         delegate operations to adaptee
    – Using Delegate Objects
          A delegate interface specifies operations the
           adapter needs to implement
Using Abstract Operations
Using Delegate Objects
Adapter - comments

   An adapter may have more than one adaptee
    – There may not be a one-to-one correspondence
      between operations of Target and those of
      Adaptee
    – So it is possible that an operation of Target is
      realized with two separate adaptee classes.
   The pattern decouples Client from adaptee.
    – When a different adaptee is needed, we only need
      to change to another adapter and the client does
      not need to change at all.
Structural Patterns - Summary

   Facade provides an interface to
    collections of objects
   Decorator adds to objects at runtime
   Composite represents trees of objects
   Proxy avoids calling expensive
    operations unnecessarily
   Adapter decouples client from an
    existing system

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:8
posted:9/3/2012
language:Latin
pages:44