1 / 37

Design Patterns (III)

Design Patterns (III). Pattern. Creational Pattern. Structural Pattern. Behavioral Pattern. Abstract Factory. Builder Pattern. Command. Command. Observer. Strategy. State. Singleton. Facade. Bridge. Composite. Proxy. A Pattern Taxonomy. Composite Pattern.

rangle
Télécharger la présentation

Design Patterns (III)

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. Design Patterns (III)

  2. Pattern Creational Pattern Structural Pattern Behavioral Pattern Abstract Factory Builder Pattern Command Command Observer Strategy State Singleton Facade Bridge Composite Proxy A Pattern Taxonomy

  3. Composite Pattern Problem: handling structures consisting of parts First solution: two-levels … if X is Composite then X.forall() else X.operation; ... * Composite Leaf children forall() operation() For all children c: c.operation() Symptoms: - Composite and leafs always treated differently in code - Difficult to extend (new kinds of leafs or composites, unrestricted depth)

  4. Developing the Composite Pattern (1) 1) Unified treatment in client and unrestricted depth of parts: children * Item íf I have children then for all children c: c.operation() else doSomething(); operation() Client: item.operation()

  5. Developing the Composite Pattern (2) 2) New types of elements: children * Item operation() íf I have children then for all children c: c.operation() else doSomething2() íf I have children then for all children c: c.operation() else doSomething1() Item2 Item1 operation() operation()

  6. Developing the Composite Pattern (3) 3) Separating the composite class: children * Item operation() Composite Item1 for all children c: c.operation() doSomeThing operation() operation()

  7. Composite Design Pattern Name: Composite Problem: How to organize hierarchical object structures so that the clients are not aware of the hierarchy? Solution: Item * children operation() Leaf Composite For all children c: c.operation() operation() operation()

  8. Composite Pattern (cont.) • Applicable when: • you want to represent part-whole hierarchies of objects • you want clients to be able to ignore the difference between composite and • elementary objects • Consequences: • Wherever a client handles a composite object it can handle an elementary • object and vice versa • Client code becomes simpler • Facilitates the adding of new composite and elementary types • May overgeneralize: does not support a structure that allows only certain kinds • of objects

  9. Composite Pattern: Example Source * children delete() print() File Folder For all children c: c.delete(); Delete folder delete() print() add(Source) delete() print()

  10. Design Patterns and UML Composite Item * Statement execute() Composite Leaf SimpleStatement Block children execute() execute()

  11. Pattern Creational Pattern Structural Pattern Behavioral Pattern Abstract Factory Builder Pattern Command Command Observer Strategy State Singleton Facade Bridge Composite Proxy A Pattern Taxonomy

  12. The Bridge Pattern • Intent • Decouple an abstraction from its implementation so that the two can very independently • This pattern is also called the handle/body idiom • Problem • Allow arithmetic operations between objects of possibly different internal representation (integer, floating-point etc.). • Let numbers adjust their internal representation automatically in response to assignment, following “standard promotion” rules. • Private and public sections of a class were designed to separate implementation from the interface. The private parts of a class are inaccessible but still visible. This visibility may cause unnecessary recompilation of clients even when only some comments are changed.

  13. The Bridge Pattern (2) • Solution • Split a design class into two class hierarchies. One represents the interface (called the handle). The other embodies the implementation, and is called the body. The handle forwards member function invocations to the body. Client Abstraction Implementor OperationImp() Operation() RefinedAbstraction ConcreteImpementor-A ConcreteImplementor-B

  14. Bridge Pattern Example • Creating a platform-independent toolkit • We want to separate the abstract drawing of a window from the native, primitive device.

  15. The Bridge Pattern (3) • Participants • Abstraction • Defines the abstraction’s interface • Maintains a reference to an object of type Implementor • Refined Abstraction • Extends the interface defined by Abstraction • Implementor • Defines the interface for implementation classes. This interface doesn’t have to correspond exactly to Abstraction’s interface; in fact the two interfaces can be quite different. Typically the Implementor interface provides only primitive operations, and Abstraction defines higher-level operations based on these primitives. • ConcreteImplementor • Implements the Implementor interface and defines its concrete implementation.

  16. The Bridge Pattern (4) • Consequences • Decoupling interface and implementation • The implementation of a class becomes hidden behind a private pointer • The implementation of an abstraction can be configured at run time • Changing an implementation class doesn’t require recompiling the Abstraction class and its clients. • Hiding implementation details from clients • Improved extensibility – the Abstraction and Implementor hierarchies can be extended independently. • The system may become slower (delegation !)

  17. Pattern Creational Pattern Structural Pattern Behavioral Pattern Abstract Factory Builder Pattern Command Command Observer Strategy State Singleton Facade Bridge Composite Proxy A Pattern Taxonomy

  18. The Facade Pattern • Intent • Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use • Motivation • Structuring a system into subsystem helps reduce complexity. A common design goal is to minimize the communication and dependencies between subsystems. • One way to achieve this goal is to introduce a façade objectthat provides a single, simplified interface to the more general facilities of a subsystem.

  19. Facade Pattern Facade

  20. Facade Pattern • Consequences • It shields clients from subsystem components, thereby reducing the number of objects that clients deal with and making the subsystem easier to use. • It promotes weak coupling between the subsystem and its clients. Weak coupling lets you vary the components of the subsystem without affecting its clients. • It reduces compilation dependencies when subsystem classes change • A façade can also simplify porting systems to other platforms, because it’s less likely that building one subsystem requires building all others. • It doesn’t prevent applications from using subsystem classes if they need to. Thus you can choose between ease of use and generality.

  21. Some more useful patterns “Tips and tricks”

  22. Prototype Pattern • The problem: • How to create more objects out of a variety of given objects without making the construction too messy. • The solution: • Make every needed object implement a “clone” method, which returns a new, identical object. • Use a set of such prototypes to create more objects. • The advantages: • Creation details are transparent to client. • Attributes are copied too – the prototype becomes a customable object factory.

  23. Prototypes example • A drawing tool: • The user has a set of shapes to create and manipulate. • Each shape can have default properties (color, etc.) • Useful for copy & paste, too! properties Shape ShapesToolBar getShape() clone() Circle Rectangle clone() clone()

  24. Template methods • The problem: • Keeping a uniform behavior of a hierarchy of classes, while letting each concrete sub-class refine the general behavior. • “Hard-coding” LSP… • The solution: • The super-class declares abstract methods and calls them inside “template methods”. • The sub-classes implement the abstract methods. • A.k.a “Beta extension”. • Advantages: • Reduces code duplication. • easier to extend base class. • Enforces some level of uniform behavior

  25. Template methods classes • For example: • We want to draw parts in specific order (the template) • But each drawing order is different (the primitives).

  26. The Visitor Pattern (1) • The problem: • How to make a method call based on the dynamic type of both the receiver and the parameter? • A.k.a “multi-method”. • Other thing: how to make a “handler” class that handles some aspect over an entire hierarchy of classes, without the need to specify the exact type to handle dynamically? • For example: • We want to make a utility that stores (or otherwise handles) different nodes in different ways, but the exact type of the node is not necessarily known.

  27. The Visitor Pattern (2) • The solution: • The “visitor” class would have a different method for each type of element required. • Each element class would have a method “accept(Visitor)” in which it would call the appropriate visitor method. • A concrete object always knows its own type… • Composite objects will send their visitor to all their sub-elements  allowing traversal! • The advantages: • Allowing a type-safe, convenient way to put responsibilities in external classes.

  28. Visitor Pattern Classes

  29. Visitor Example – Compiler Nodes

  30. Design Patterns – Summing up

  31. Patterns of patterns (1) • “It’s OK to make classes for totally abstract notions, not just real-world objects” • Strategy, commands, visitors… • OOP models the software, not the world. • “It’s OK to hide the dirt under the rug, as long as the rug is pretty” • Façade, adapters, factories… • The mess is not always avoidable, but it doesn’t have to be exposed or used.

  32. Patterns of patterns (2) • “If you don’t know something, ask someone who does know.” • Ask the parent • Basic use of abstract code base. • Ask the children • Template methods, prototypes. • Ask someone from a family who does know • In other words: delegate responsibility to a different hierarchy  almost all patterns. • Factory, bridge, state, strategy, visitor…

  33. Complaints against patterns (1) • “Patterns are inefficient” • Actually, complex control code is also very inefficient, due to inability to optimize and frequent cache misses. • Most GUI applications spend ~90% of their time waiting for user input anyway. • “Patterns code is difficult to understand” • In the long run, it is simpler then a couple of thousands lines long “good-old” control code. • Good documentation can help. • “We end up with lots of small classes” • Better then ending up with a single really big one. • Classes should be easily navigable – use good tools!

  34. Complaints against patterns (2) • “We don’t have the time to do it” • If you can’t do it right the first time, from where would you take the time to do it again? • Improve your code as you debug or maintain it (instead of constantly hacking it) • “No broken windows” • Refactoring • “No-one will understand our code but us” • That means they can’t fire you… • “How to write unmaintainable code” http://mindprod.com/unmain.html

  35. Summary • Structural Patterns • Focus: How objects are composed to form larger structures • Problems solved: • Realize new functionality from old functionality, • Provide flexibility and extensibility • Behavioral Patterns • Focus: Algorithms and the assignment of responsibilities to objects • Problem solved: • Too tight coupling to a particular algorithm • Creational Patterns • Focus: Creation of complex objects • Problems solved: • Hide how complex objects are created and put together

  36. Conclusion • Design patterns • Present in a systematic way proven good design solutions to common problems • Apply the same principles to structure and to behavior. • Design patterns solve all your software engineering problems • Use a design pattern only after recognizing the problem • Don’t turn design patterns into a religion • Design patterns are not God-given: modify them if needed • Design patterns are about common sense – use them with common sense

  37. Cargill’s Quandary “All software design problems can be solved by adding additional levels of indirection, except of too many levels of indirection.”

More Related