1 / 29

CSC 7322 : Object Oriented Development J Paul Gibson, A207 paul.gibson@int-edu.eu

CSC 7322 : Object Oriented Development J Paul Gibson, A207 paul.gibson@int-edu.eu http://www-public. it-sudparis.eu /~gibson/Teaching/CSC7322/. Design Patterns Revisited …/~ gibson / Teaching /CSC7322/L13-DesignPatterns-2.pdf. Learning by PBL – the patterns selected.

teal
Download Presentation

CSC 7322 : Object Oriented Development J Paul Gibson, A207 paul.gibson@int-edu.eu

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSC 7322 : Object OrientedDevelopment J Paul Gibson, A207 paul.gibson@int-edu.eu http://www-public.it-sudparis.eu/~gibson/Teaching/CSC7322/ Design Patterns Revisited …/~gibson/Teaching/CSC7322/L13-DesignPatterns-2.pdf TSP: Software Engineering

  2. Learning by PBL – the patterns selected Singleton - creational Iterator – behavioural Visitor – behavioural Proxy - structural Factory - creational Decorator – structural Facade - structural Adapter - structural Chain Of Responsibility - behavioural MVC – a composite pattern (Strategy, Observer, Composite) TSP: Software Engineering

  3. Decorator Pattern See - http://sourcemaking.com/design_patterns/decorator • Intent • Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. • Client-specified embellishment of a core object by recursively wrapping it. • Wrapping a gift, putting it in a box, and wrapping the box. • Problem • You want to add behavior or state to individual objects at run-time. • Inheritance is not feasible because it is static and applies to an entire class. TSP: Software Engineering

  4. Decorator Pattern See - http://sourcemaking.com/design_patterns/decorator Relation to other patterns Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface. Adapter changes an object’s interface, Decorator enhances an object’s responsibilities. Decorator is thus more transparent to the client. As a consequence, Decorator supports recursive composition, which isn’t possible with pure Adapters. Composite and Decorator have similar structure diagrams, reflecting the fact that both rely on recursive composition to organize an open-ended number of objects. A Decorator can be viewed as a degenerate Composite with only one component. However, a Decorator adds additional responsibilities - it isn’t intended for object aggregation. TSP: Software Engineering

  5. Decorator Pattern See - http://sourcemaking.com/design_patterns/decorator Relation to other patterns Decorator is designed to let you add responsibilities to objects without subclassing. Composite’s focus is not on embellishment but on representation. These intents are distinct but complementary. Consequently, Composite and Decorator are often used in concert. Composite could use Chain of Responsibility to let components access global properties through their parent. It could also use Decorator to override these properties on parts of the composition. Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests. Decorator lets you change the skin of an object. Strategy lets you change the guts. Most of these patterns use a form of delegation (which is not usually considered a pattern in its own right) TSP: Software Engineering

  6. Decorator Pattern Class Diagram UML The following diagram shows structure of typical decorator pattern, the diagram was taken dofactory.com TSP: Software Engineering

  7. Decorator Pattern Class Diagram UML The following diagram shows a concrete example of an Account (from http://blog.decarufel.net/2009/09/using-decorator-or-wrapper-design.html) TSP: Software Engineering

  8. Decorator Pattern Sequence Diagram UML The following diagram shows a concrete example of Account dynamic behaviour TSP: Software Engineering

  9. Decorator Pattern Sequence Diagram UML: explanation Call Bank.CreateAccount. The Bank instantiates an Account class. The Bank creates an AccountDepositValidator and wrap Account with it The Bank return an instance of IAccount. Deposit is called on IAccount which is an instance of AccountDepositValidator AccountDepositValidator calls Validate AccountDepositValidator call GetValidations to retrieve the list of validation to evaluate An AmountGreaterThaZeroValidation is created IsValid returns true AccountDepositValidator call base Deposit method Balance value is updated TSP: Software Engineering

  10. DecoratorProblem : The classic Christmas tree (revisited) Problem: Examine the Java code in the package p_decorator in the folder Patterns (~gibson/Teaching/CSC7322/Code/Decorator.zip) TSP: Software Engineering

  11. Decorator – Christmas Tree packagespecifications; publicinterfaceBranchOfTreeSpecification { publicvoidanimate(); public String getDecorations(); } TSP: Software Engineering

  12. Decorator – Christmas Tree packagespecifications; publicabstractclassBranchDecoratorSpecifiationimplementsBranchOfTreeSpecification{ protectedBranchOfTreeSpecificationdecoratedBranch; publicBranchDecoratorSpecifiation(BranchOfTreeSpecificationbranchToDecorate){ decoratedBranch= branchToDecorate; } publicvoidanimate(){decoratedBranch.animate(); } } TSP: Software Engineering

  13. Decorator- Christmas Tree packagemodels; importspecifications.BranchOfTreeSpecification; publicclassUndecoratedBranchimplementsBranchOfTreeSpecification{ publicvoidanimate(){} public String getDecorations(){ return""; } } TSP: Software Engineering

  14. Decorator - Christmas Tree packagemodels; importspecifications.BranchDecoratorSpecification; importspecifications.BranchOfTreeSpecification; publicclassBallDecoratorextendsBranchDecoratorSpecification{ booleanspinning; publicBallDecorator(BranchOfTreeSpecificationbranchOfTree){ super(branchOfTree); spinning = true; } public String getDecorations(){ String str = decoratedBranch.getDecorations(); if (spinning) str = str +" Spinning"; str = str+ " Ball."; returnstr; } publicvoidanimate(){ decoratedBranch.animate(); spinning = !spinning; } } TSP: Software Engineering

  15. Decorator– Christmas Tree packagemodels; importspecifications.BranchDecoratorSpecifiation; importspecifications.BranchOfTreeSpecification; publicclassLightsDecoratorextendsBranchDecoratorSpecifiation{ String colour;publicLightsDecorator(BranchOfTreeSpecificationbranchOfTree){ super(branchOfTree); colour= "red"; } public String getDecorations(){ String str = decoratedBranch.getDecorations(); str =str+ " colour = "+colour; returnstr; } publicvoidanimate(){ decoratedBranch.animate(); if (colour.equals("red")) colour ="white"; elseif (colour.equals("white")) colour ="blue"; elsecolour = "red"; } } TSP: Software Engineering

  16. Decorator– Christmas Tree publicclassTestBallDecorator { publicstaticvoid main (String [] args){ BranchOfTreeSpecificationplainBranch = newUndecoratedBranch(); BranchOfTreeSpecificationdecoratedBranch = newBallDecorator( plainBranch); BranchOfTreeSpecificationreDecoratedBranch = newBallDecorator( newBallDecorator( plainBranch)); System.out.println("plainBranch.getDecorations() ="+plainBranch.getDecorations()); System.out.println("decoratedBranch.getDecorations() ="+decoratedBranch.getDecorations()); System.out.println("reDecoratedBranch.getDecorations() =" +reDecoratedBranch.getDecorations()); plainBranch.animate(); System.out.println("plainBranch.animate.getDecorations() ="+plainBranch.getDecorations()); decoratedBranch.animate(); System.out.println("decoratedBranch.animate.getDecorations() ="+decoratedBranch.getDecorations()); reDecoratedBranch.animate(); System.out.println("reDecoratedBranch.animate.getDecorations() =" +reDecoratedBranch.getDecorations()); } } TSP: Software Engineering

  17. Decorator - Christmas Tree TSP: Software Engineering

  18. Decorator – Christmas Tree • TO DO: • Test Lights Decoration • Test Lights withBallsDecoration • Add new Decoration (Stars, eg) • Test 3 Decorationstogether • Create XMAS treewith 4 branches: • 2 Lights and 2 Balls • 2 Lights and 3 Stars • 2 Stars and 3 Balls • 2 Lights and 2 Stars and 2 Balls • PROBLEM: Ensurethat the state of decorations on the samebranch of treeisco-ordinated (but not necessarily on different branches) • OPTION: Maximum number of decorations on anybranchis 6 TSP: Software Engineering

  19. Decorator– Christmas Tree What to learnfrom the problem: If youreallyneed multiple instances of samedecorationthenthis pattern isprobably not correct. The following 4 sentences seemequivalent but maylead to different designs/implementations: The branch « is a » branchwith lights and stars The branch « is a » branchwith lights and « is a » branchwith stars The branch « has » lights and stars The branch « has » lights and the branch « has » stars Knowingwhich design is best depends on knowingpreciselywhatis the intended/requiredbehaviour. The decoratoris not intended to allowstatementslike: The branch « is a » branchwithlights and « is a » branchwithlights TSP: Software Engineering

  20. Decorator – Christmas Tree • Solving the problem: • If wereallyneed multiple decorations of the same type on a single branch do not use the decorator pattern in thisway • Weshouldfix the decorator pattern sothatdecorating a branchwithballbehaviourthat has already been decoratedwithballbehaviouriseither: • Handled by an exception, or • Ignored • TO DO – implement one of these solutions, and retest the new behaviour NOTE: As requirements change youmaybetempted to compromise your system by holding on to a pattern whichis no longer appropriate TSP: Software Engineering

  21. Facade versus Adapter Intuitively, what are the differences? TSP: Software Engineering

  22. Facade versus Adapter TSP: Software Engineering

  23. Facade versus Adapter TSP: Software Engineering

  24. Facade - provides a unified interface to a set of interfaces in a subsystem Identify a simpler, unified interface for the subsystem/component. Design a ‘wrapper’ class that encapsulates the subsystem. The facade/wrapper captures the complexity and collaborations of the component, and delegates to the appropriate methods. The client uses (is coupled to) the Facade only. Facade defines a new interface, whereas Adapter uses an old interface. Remember that Adapter makes two existing interfaces work together as opposed to defining an entirely new one. TSP: Software Engineering

  25. Adapter - letsclasses work together that couldn’t otherwise because of incompatible interfaces Identify the players: the component(s) that want to be accommodated (i.e. the client), and the component that needs to adapt (i.e. the adaptee). Identify the interface that the client requires. Design a “wrapper” class that can “impedance match” the adaptee to the client. The adapter/wrapper class “has a” instance of the adaptee class. The adapter/wrapper class “maps” the client interface to the adaptee interface. The client uses (is coupled to) the new interface TSP: Software Engineering

  26. Realation to Other Design Patterns Adapter and Facade are both wrappers; but they are different kinds of wrappers. The intent of Facade is to produce a simpler interface, and the intent of Adapter is to design to an existing interface. While Facade routinely wraps multiple objects and Adapter wraps a single object; Facade could front-end a single complex object and Adapter could wrap several legacy objects. Adapter makes things work after they’re designed; Bridge makes them work before they are. Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to make unrelated classes work together. Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface. TSP: Software Engineering

  27. The Rectangle Problem Alegacy Rectangle component’s display() methodexpects to receive “x, y, w, h” parameters. But the client wants to pass “upperleft x and y” and “lower right x and y”. This mismatchcanbereconciled by using a design pattern. Question: isthissuitable for an adapter or a facade (or somethingelse) Draw the UML design and implement in Java TSP: Software Engineering

  28. Chain of responsibility • Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. TSP: Software Engineering

  29. Chain of responsibility Note: Chain of Responsibility can use Command to represent requests as objects THIS MAY BE USEFUL IN YOUR OO PROJECT TSP: Software Engineering

More Related