1 / 35

Design Patterns

Design Patterns. Becoming Good OO Developers. Developing good OO Software is hard Takes a lot of time to take advantage of all OO features Lots of Experience needed to become good designers Many systems are not leveraging OO advantages

humphrey
Download Presentation

Design Patterns

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

  2. Becoming Good OO Developers • Developing good OO Software is hard • Takes a lot of time to take advantage of all OO features • Lots of Experience needed to become good designers • Many systems are not leveraging OO advantages • To master OO software design, study experienced developers design • Reuse proven software design • => Patterns can help

  3. Design Tips & Hints (High level Patterns) • Layering • Improves stability, understandability, flexibility • Reduces impact to changes • Restrict dependencies/coupling between packages/subsystems • GUI (Boundary Classes) separated in one layer/package • Allow the User Interface to change without impacting the rest of the system • Package Functionally related Classes • Changes in one Class impact the other Class • Rich Interaction between Classes • Package should be cohesive • Reuse proven software design • => Patterns can help

  4. Design

  5. Design • Refine the Class Diagram • Structure system • Subsystems, Interfaces, Classes • Define subsystems dependencies • Capture major interfaces between subsystems • Assign responsibilities to new design classes • Describe realization of Use Cases • Use Sequence and Collaboration Diagrams • Assign visibility to class attributes • Define Methods signature • Develop State diagram for relevant design classes • Use Interaction Diagram to distribute behavior among classes • Use Design Patterns for parts of the system

  6. Design Patterns • Definition • abstract a recuring design structure • common solution to a common problem in a given context • specify structure and behavior of a society of classes • describe ways a cluster of classes work together to accomplish a goal • a way to package and reuse design experience • Advantages • Codify existing knowledge about how to use good design practices • Naming a design concept helps understands the problem/solution • Facilitates communication among team members

  7. Goals of Design Patterns • Codify good Design • distill and disseminate experience • aid novices and experts • Give design structures explicit names • common vocabulary • Capture Design information • Improve Documentation • Expose Design Decision

  8. Essential Elements of a Pattern NAME - • a handle for identifying a design problem, its solution and consequences • increases vocabulary PROBLEM - • places where the pattern is applicable SOLUTION - • the elements that make up the design, their relationships, responsibilities and interactions CONSEQUENCES - • the results and tradeoffs of applying the pattern (pros and cons)

  9. Model View Controller Pattern • the archetypal pattern • popularized in Smalltalk systems • is used to build user interfaces • is composed of three kinds of objects - • creates application data to be displayed MODEL • handles the presentation of data VIEW • defines the user interface’s reaction to user input CONTROLLER • serves to decouple views from models

  10. Window Window Window MVC Pattern Views a b c b x 60 30 10 y 50 30 20 z 80 10 10 a c a b c a = 50% b = 30% c = 20% model

  11. Elements of a Pattern Description • Pattern Name and Classification • Intent: short description and purpose • Also Known As: other names used • Motivation: motivating scenario demonstrating pattern’s use • Applicability: circumstances in which pattern applies • Structure : graphical representation of the pattern using UML • Participants: classes and objects and their responsibilities • Collaborations: how participants cooperate • Consequences: results of applying the pattern, pro and con • Implementation: language dependent issues such as hints, pitfalls or technique • Sample Code: sample implementatio • Known Uses: real systems using it • Related Patterns: how other patterns relate to it.

  12. Pattern Example: Observer • Intent: • define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically • Applicability: • when an object is defined in one way but presented in many ways • when there is a one-to-many dependency to enforce • Participants: • Subject: knows its Observers. Any numbers can observe a subject • Observer: defines an interfacefor updating objects • Concrete Subject: stores state of interest, sends notification to observers • Concrete Observer: maintains a ref to ConcreteSubject, stores state of interest, implements updating mechanism to keep states consistent

  13. for all o in observers { o->update() } Observer Pattern Structure Observer Subject observers * Update() Attach(observer) Detach(observer) notify() Concrete Subject Concrete Observer subject subjectState observerState Update() GetState() observerState= subject->GetState() return subjectState

  14. Observer Pattern Interactions :aConcrete Observer :anotherConcrete Observer :aConcrete Subject setState() notify() Update() GetState() Update() GetState()

  15. Pattern Example: Observer • Collaborations: • ConcreteSubject notifies its Observers whenever a change occurs • After being informed of a change in the concreteSubject, the concreteObserver querries the subject for information, and updates its state to reconcile it with Subject’s State • Consequences: • Subject and Observers may vary independently, only abstract coupling • Can reuse one without the other • Can add Observers without any change • Known Uses: • MVC • Interviews • MFC

  16. Pattern Example: Observer • Implementation: • Mapping subjects to their observers • Observing more than one subject • who triggers the update? • dangling references to deleted subjects • Subject State consistency before notification

  17. Pattern Classification PURPOSE Creational • patterns which are concerned with the process of object creation • patterns which deal with composition of classes or objects Structural • patterns which characterize the responsibilities of objects and classes Behavioral SCOPE Class • patterns which deal with relationships between classes and their subclasses • patterns which deal with relation-ships between objects Object

  18. Creational Patterns Abstract Factory - provides an interface for creating families

  19. Structural Patterns Adapter - converts the interface of a class into another interface that clients expect. It lest classes work together that could not otherwise because of incompatible interfaces Bridge - decouples an abstraction from its implementation so that the two can vary independently Composite - compose objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and compositions of objects uniformly Decorator - allows additional responsibilities to be attached to an object dynamically. It provides a flexible alternative to subclassing for extending functionality Facade - provides a unified interface to a set of interfaces in a subsystem. It defines a higher-level interface that makes the subsystem easier to use Flyweight - uses a sharing scheme to support large numbers of fine grained objects efficiently Proxy - controls access to an object by providing a surrogate or placeholder

  20. Behavioral Patterns Chain of Responsibility - avoids coupling the sender of a request to its receiver by giving more than one object a chain to handle the request. The receiving objects are chained, and the request passed along the chain until it is handled Command - encapsulates a request as an object, thus allowing clients to be parameterized by different requests, to dequeue or log requests and to support undoable operations Interpreter - defines a representation for a language's grammar and an interpreter that uses the representation to interpret sentences in the language Iterator - provides a way to access the elements of an aggregate object sequentially, without exposing its underlying implementation Mediator - defines an object that encapsulates how a set of objects interact. It promotes loose coupling by keeping objects from referring to each other explicitly, and allowing their interactions to be varied independently Memento - captures and externalizes an object’s internals, without violating encapsulation, so that the object can be resorted to this state later

  21. Behavioral Patterns (Continued) Observer- defines a one-to-many dependency between objects so that when one object changes its state, all its dependents are notified and updated automatically State - Allows an object to alter its behavior when its internal state changes. The object appears to change its class Strategy - defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from clients that use it Template Method - defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure Visitor - represents an operation to be performed on the elements of an object structure. It lets you define a new operation without changing the classes of the elements on which it operates

  22. Selecting a Design Pattern • consider how design patterns solve design problems • scan the “intent” sections • study how patterns interrelate • study patterns of like purpose • examine a cause of redesign • consider what should be variable in the design

  23. Using a Design Pattern • 1.read pattern description for an overview • 2. study Structure, Participants and Collaborations sections • 3. look at the Sample Code section • 4. choose participant names for application context • 5. define the classes • 6. define application-specific names for operations • 7. implement operation to carry out responsibilities

  24. Abstract Factory Pattern • provides an interface for creating families of related or dependent objects without specifying their concrete classes INTENT • Kit AKA • a system should be independent of how its products are created, composed and represented • a system should be configured with one of multiple families of products • a family of related products is designed to be used together, and you need to enforce this constraint • you want to provide a class library of products, and you want to reveal just their interface, not their implementations USE WHEN • concrete factories are often singletons • can be implemented by Factory Method or Prototype RELATED

  25. Abstract Factory Pattern Continued • AbstractFactory • ConcreteFactory • AbstractProduct • ConcretePoduct • Client PARTICIPANTS • normally a single instance of ConcreteFactory is created at runtime. This concrete factory creates product objects having a particular implementation. To create different product objects, clients should use a different concrete factory • AbstractFactory defers creation of product objects to its ConcreteFactory COLLABORATIONS • concrete classes are isolated • exchanging product families is easy CONSEQUENCES KNOWN USES • Interviews (Kit suffix denotes abstract factories) • ET++

  26. Abstract Factory Structure Client AbstractProductA AbstractFactory ProductA2 ProductA1 CreateProductA() CreateProductB() AbstractProductB ConcreteFactory1 ConcreteFactory2 CreateProductA() CreateProductB() CreateProductA() CreateProductB() ProductB2 ProductB1

  27. Abstract Factory Example Client Window WidgetFactory MotifWindow PMWindow CreateScrollBar() CreateWindow() ScrollBar MotifWidgetFactory PMWidgetFactory CreateScrollBar() CreateWindow() CreateScrollBar() CreateWindow() PMScrollBar MotifScrollBar

  28. Strategy Pattern • defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it INTENT • Policy AKA • many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors • different variants of an algorithm are required • an algorithm uses data that clients should not know about. The strategy pattern can be used to avoid exposing complex, algorithm-specific data structures • a class defines many behaviors, and these appear as multiple conditional statements in its operations. The related conditional branches can be moved into their own strategy class USE WHEN • strategy objects often make good flyweights RELATED

  29. Strategy Pattern Continued • Strategy • ConcreteStrategy • Context PARTICIPANTS • Strategy and Context interact to implement the chosen algorithm • a context forwards requests from its clients to its strategy COLLABORATIONS • families of related algorithms are available • provide an alternative to subclassing • no conditional statements for selecting behavior • provide different implementations • clients must be aware of different strategies • communication overheads • Increased number of objects CONSEQUENCES • Interviews ET++ for line breaking algorithms KNOWN USES

  30. Strategy Structure strategy Context Strategy ContextInterface() AlgorithmInterface() ConcreteStrategyA ConcreteStrategyB ConcreteStrategyC AlgorithmInterface() AlgorithmInterface() AlgorithmInterface()

  31. Composite Structure Component Client Operation() Add(component) Remove(Component) GetChild(int) children Leaf Composite forall g in children g.Operation Operation() Operation() Add(component) Remove(Component) GetChild(int)

  32. Typical Composite Object Structure aComposite aLeaf aLeaf aComposite aLeaf aLeaf aLeaf aLeaf

  33. Typical Example of Composite Graphic Draw() Add(Graphic) Remove(Graphic) GetChild(int) graphics Rectangle Line Text Picture forall g in graphics g.Operation Draw() Draw() Draw() Draw() Add(Graphic g) Remove(Graphic) GetChild(int) add g to list of graphics

  34. Recursively Composed Graphics Objects aPicture aPicture aLine aRectangle aLine aText aRectangle

  35. Frameworks • Integrated set of components that collaborate to provide a reusable architecture for a family of related applications • Ex: Microsoft Foundation Classes, ACE • Enable direct reuse of code • Facilitate large scale reuse • High inital learning curve

More Related