Design Patterns UML Patterns 1 Becoming Good OO
Design Patterns UML - Patterns 1
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 UML - Patterns 2
Design Tips & Hints (High level Patterns) • Layering m Improves stability, understandability, flexibility m Reduces impact to changes m Restrict dependencies/coupling between packages/subsystems • GUI (Boundary Classes) separated in one layer/package m Allow the User Interface to change without impacting the rest of the system • Package Functionally related Classes m Changes in one Class impact the other Class m Rich Interaction between Classes • Package should be cohesive m • Reuse proven software design • => Patterns can help UML - Patterns 3
Design UML - Patterns 4
Design • Refine the Class Diagram • Structure system m • • Subsystems, Interfaces, Classes Define subsystems dependencies Capture major interfaces between subsystems Assign responsibilities to new design classes Describe realization of Use Cases m 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 UML - Patterns 5
Design Patterns 1. 2. Definition m abstract a recuring design structure m common solution to a common problem in a given context m specify structure and behavior of a society of classes m describe ways a cluster of classes work together to accomplish a goal m a way to package and reuse design experience Advantages m Codify existing knowledge about how to use good design practices m Naming a design concept helps understands the problem/solution m Facilitates communication among team members UML - Patterns 6
Goals of Design Patterns l l Codify good Design m distill and disseminate experience m aid novices and experts Give design structures explicit names m l common vocabulary Capture Design information m Improve Documentation m Expose Design Decision UML - Patterns 7
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) UML - Patterns 8 8
Model View Controller Pattern m the archetypal pattern m popularized in Smalltalk systems m is used to build user interfaces m is composed of three kinds of objects MODEL VIEW CONTROLLER n - creates application data to be displayed - handles the presentation of data - defines the user interface’s reaction to user input serves to decouple views from models UML - Patterns 9 9
MVC Pattern Views Window a Window b Window c x 60 30 10 y 50 30 20 z 80 10 10 b a a b c c a = 50% b = 30% c = 20% model UML - Patterns 10 10
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. UML - Patterns 11 11
Pattern Example: Observer l Intent: define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically m l Applicability: when an object is defined in one way but presented in many ways m m l when there is a one-to-many dependency to enforce Participants: Subject: knows its Observers. Any numbers can observe a subject m m Observer: defines an interfacefor updating objects Concrete Subject: stores state of interest, sends notification to observers m UML - Patterns 12
Observer Pattern Structure Subject Attach(observer) Detach(observer) notify() Observer observers * for all o in observers { o->update() } Concrete Subject subject. State Get. State() Update() subject Concrete Observer observer. State Update() observer. State= subject->Get. State() return subject. State UML - Patterns 13
Observer Pattern Interactions : a. Concrete Observer : a. Concrete Subject : another. Concrete Observer set. State() notify() Update() Get. State() UML - Patterns 14
Pattern Example: Observer l Collaborations: Concrete. Subject notifies its Observers whenever a change occurs m After being informed of a change in the concrete. Subject, the concrete. Observer querries the subject for information, and updates its state to reconcile it with Subject’s State m l Consequences: Subject and Observers may vary independently, only abstract coupling m l m Can reuse one without the other m Can add Observers without any change Known Uses: m MVC m Interviews UML - Patterns 15
Pattern Example: Observer l Implementation: m Mapping subjects to their observers Observing more than one subject m who triggers the update? m m dangling references to deleted subjects m Subject State consistency before notification UML - Patterns 16
Pattern Classification PURPOSE Creational Structural Behavioral - patterns which are concerned with the process of object creation - patterns which deal with composition of classes or objects - patterns which characterize the responsibilities of objects and classes SCOPE Class Object - patterns which deal with relationships between classes and their subclasses - patterns which deal with relationships between objects UML - Patterns 17 17
Creational Patterns Abstract Factory - provides an interface for creating families UML - Patterns 18 18
Structural Patterns Adapter - Bridge Composite - Decorator - Facade - Flyweight Proxy - 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 decouples an abstraction from its implementation so that the two can vary independently compose objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and compositions of objects uniformly allows additional responsibilities to be attached to an object dynamically. It provides a flexible alternative to subclassing for extending functionality provides a unified interface to a set of interfaces in a subsystem. It defines a higher-level interface that makes the subsystem easier to uses a sharing scheme to support large numbers of fine grained objects efficiently controls access to an object by providing a surrogate or placeholder UML - Patterns 19 19
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 UML - Patterns 20 20
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 UML - Patterns 21 21
Selecting a Design Pattern m consider how design patterns solve design problems m scan the “intent” sections m study how patterns interrelate m study patterns of like purpose m examine a cause of redesign m consider what should be variable in the design UML - Patterns 22 22
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 UML - Patterns 23 23
Abstract Factory Pattern INTENT - provides an interface for creating families of related or dependent objects without specifying their concrete classes AKA - Kit USE WHEN - 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 RELATED - concrete factories are often singletons - can be implemented by Factory Method or Prototype UML - Patterns 24 24
Abstract Factory Pattern Continued COLLABORATIONS PARTICIPANTS Abstract. Factory Concrete. Factory Abstract. Product Concrete. Poduct Client normally a single instance of Concrete. Factory 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 - Abstract. Factory defers creation of product objects to its Concrete. Factory CONSEQUENCES KNOWN USES - concrete classes are isolated exchanging product families is easy Interviews (Kit suffix denotes abstract factories) ET++ UML - Patterns 25 25
Abstract Factory Structure Client Abstract. Product. A Abstract. Factory Create. Product. A() Create. Product. B() Product. A 2 Product. A 1 Abstract. Product. B Concrete. Factory 1 Concrete. Factory 2 Create. Product. A() Create. Product. B() Product. B 2 UML - Patterns Product. B 1 26 26
Abstract Factory Example Client Window Widget. Factory Create. Scroll. Bar() Create. Window() PMWindow Motif. Window Scroll. Bar Motif. Widget. Factory Create. Scroll. Bar() Create. Window() PMScroll. Bar UML - Patterns Motif. Scroll. Bar 27 27
Strategy Pattern INTENT AKA - defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it - Policy USE WHEN - 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 RELATED - strategy objects often make good flyweights UML - Patterns 28 28
Strategy Pattern Continued COLLABORATIONS PARTICIPANTS Strategy Concrete. Strategy Context Strategy and Context interact to implement the chosen algorithm - a context forwards requests from its clients to its strategy CONSEQUENCES - families of related algorithms are available KNOWN USES 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 - Interviews ET++ for line breaking algorithms UML - Patterns 29 29
Strategy Structure strategy Context. Interface() Strategy Algorithm. Interface() Concrete. Strategy. A Concrete. Strategy. B Concrete. Strategy. C Algorithm. Interface() UML - Patterns 30 30
Composite Structure Component Client Operation() Add(component) Remove(Component) Get. Child(int) children Leaf Composite Operation() Add(component) Remove(Component) Get. Child(int) UML - Patterns forall g in children g. Operation 31 31
Typical Composite Object Structure a. Composite a. Leaf UML - Patterns a. Leaf 32 32
Typical Example of Composite Graphic Draw() Add(Graphic) Remove(Graphic) Get. Child(int) graphics Rectangle Line Text Picture Draw() Add(Graphic g) Remove(Graphic) Get. Child(int) UML - Patterns forall g in graphics g. Operation add g to list of graphics 33 33
Recursively Composed Graphics Objects a. Picture a. Line a. Text a. Line a. Rectangle UML - Patterns 34 34
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 UML - Patterns 35
- Slides: 35