Oct, 16, Design Patterns PROBLEM CONTEXT SOLUTION A design pattern documents a proven solution to a recurring problem in a specific context and its consequences.
Oct, 16, References F 1. Design Patterns, Elements of Reusable Object- Oriented Software, –Erich Gamma –Richard Helm –Ralph Johnson –John Vlissides –Addison-Wesley F 2. Java Design Patterns: A tutorial –James W. Cooper
Oct, 16, Essential Elements F The pattern name F The problem F The solution F The consequences
Oct, 16, Describing Design Patterns F Pattern Name and Classifications F Intent F Also Known As F Motivation F Applicability F Structure F Participants F Collaborations F Consequences F Implementation F Sample Code F Known Uses F Related Patterns
Oct, 16, The Catalog of Design Patterns
Oct, 16, Creational Patterns F Abstract the instantiation process F Make system independent of how its object are created, composed, and represented. F Creational class patterns use inheritance to vary the class that’s instantiated. –Factory Method F Creational object patterns delegate instantiation to another object. –Abstract Factory, Builder, Prototype, Singleton.
Oct, 16, Factory Method -Class Creational F Intent: define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. F Also Known As: Virtual Constructor
Oct, 16, Factory Method -Applicability F A class can’t anticipate the class of objects it must create. F A class wants its subclasses to specify the objects it creates. F Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
Oct, 16, Factory Method -Structure Product ConcreteProduct Creator FactortMethod() AnOperation() ConcreteCreator FactoryMethod()
Oct, 16, Factory Method -Participants F Product:defines the interface of objects the factory method creates. F ConcreteProduct: implements the Product interface F Creator: declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns default ConcreteProduct object; may call the factory method to create a Product object. F ConcreteCreator: overrides the factory method to return an instance of a ConcreteProduct.
Oct, 16, Factory Method F Collaborations –Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct. F Consequences –Provide hooks for subclasses. –Connects parallel class hierarchies.
Oct, 16, Factory Method -Implementation F Two major varieties: (1) when the Creator class is an abstract class and does not provide an implementation for the factory method it declares; (2)when the Creator is a concrete class and provides a default implementation for the factory method. F Parameterized factory methods. F Language-specific variants and issues. F Using templates to avoid subclassing. F Naming conventions.
Oct, 16, Abstract Factory Object Creational F Intent: provide an interface for creating families of related or dependent objects without specifying their concrete classes. F Also Known As: kit F Motivation:..
Oct, 16, Abstract Factory -Applicability F A system should be independent of how its products are created, composed, and represented. F A system should be configured with one of multiple families of products. F A family of related product objects is designed to be used together, and you need to enforce this constraint. F You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.
Oct, 16, Abstract Factory -Structure AbstractFactory CreateProductA() CreateProductB() ConcreteFactory1 CreateProductA() CreateProductB() ConcreteFactory2 CreateProductA() CreateProductB() AbstractProductA ProductA2ProductA1 AbstractProductB ProductB2ProductB1 Client
Oct, 16, Abstract Factory -Participants F AbstractFactory: declares an interface for operations that create abstract product objects. F ConcreteFactory: implements the operations to create concrete product objects. F AbstractProduct: declares an interface for a type of product object. F ConcreteProduct: defines a product object to be created by the corresponding concrete factory; implements the ABstractProduct interface. F Client: uses only interfaces declared by AbstractFactory and AbstractProduct.
Oct, 16, Abstract Factory -Collaborations F Normally a single instance of a ConcreteFactory class is created at run- time.This concrete factory creates product objects having a particular implementation. To create different product objects, clients should use a different concrete factory. F AbstractFactory defers creation of product objects to its ConcreteFactory subclass.
Oct, 16, Abstract Factory -Consequences F It isolates concrete classes. F It makes exchanging product families easy. F It promotes consistency among products. F Supporting new kinds of products is difficult.
Oct, 16, Abstract Factory -Implementation F Factories as singletons. F Creating the products. F Defining extensible factories.
Oct, 16, Singleton -Object Creational F Intent: Ensure a class only has one instance, and provide a global point of access to it. F Applicability –There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point. –When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.
Oct, 16, Consequences F Controlled access to sole instance. F Reduced name space. F Permits refinement of operations and representation. F Permits a variable number of instances. F More flexible than class operation.
Oct, 16, Builder -Object Creational F Intent: Separate the construction of a complex object from its representation so that the same construction process can create different representations. F Applicability: when –The algorithm for creating a complex object should be independent of the parts that make up the object and how they are assembled. –The construction process must allow different representations for the object that is constructed.
Oct, 16, Builder -Structure
Oct, 16, Participants F Builder: specifies an abstract interface for creating parts of a Product object. F ConcreteBuilder: –Constructs and assembles parts of the product by implementing the Builder interface. –Defines and keeps track of the representing it creates. –Provides an interface for retrieving the product. F Director: constructs an object using the Builder interface. F Product –Represents the complex object under construction. ConcreteBuilder builds the product’s internal representation and defines the process by which it’s asembled. –Includes classes that define the constituent parts, including interfaces for assembling the parts into the final results.
Oct, 16, Consequences F It lets you vary a product’s internal representation. F It isolates code for construction and representation. F It gives you finer control over the construction process.
Oct, 16, Implementation F Assembly and construction interface. F Why no abstract class for products? F Empty methods as default in Builder.
Oct, 16, Prototype -Object Creational F Intent: Specifies the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
Oct, 16, Prototype F Applicability: –When the classes to instantiate are specified at run- time, for example, by dynamic binding; and –To avoid building a class hierarchy of factories that parallels the class hierarchy of products; or –When instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.
Oct, 16, Participants F Prototype –Declares an interface for cloning itself. F ConcretePrototype –Implements an operation for cloning itself. F Client –Creaets a new object by asking a prototype to clone itself.
Oct, 16, Structure
Oct, 16, consequences F Adding and removing products at run-time. F Specifying new objects by varying values. F Specifying new objects by varying structure. F Reduced subclassing F Configuring an application with classes dynamically.
Oct, 16, Implementation F Using a prototype manager. F Implementing the Clone operation. F Initializing clones.
Oct, 16, Structural Patterns F Focus on how classes and objects are composed to form larger structures. F Structural class patterns use inheritance to compose interfaces or implementations, while structural object patterns describe ways to compose objects to realize new functionality.
Oct, 16, Adapter -Class, Object Structural F Intent: Convert the interface of a class into another interface client expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
Oct, 16, Class Adapter - Structure
Oct, 16, Class Adapter F Applicability –You obtain a target class, which you need to use in your designs, but, the public interface of the target class (it’s methods) does not match your requirements or it does not fit into the necessary class inheritance hierarchy. F Solution –Create an abstract interface ancestor class that implements the interchangeable interface that clients expect –Create an adapter subclass of the interface class. –Multiply inherit the adapter class from the target class to automatically include both its implementation. –Override the methods from the interface class in the adapter class to call the methods in the target class. F Consequences –The Adapter may optionally override behavior in the Target class. –Minimizes the number of new objects required –The Adapter class may also be used in designs which expect a Target class. –Cannot be used to adapt Target and its subclasses. Only the Target class itself can be adapted. –This technique cannot be used in languages that do not support multiple inheritance
Oct, 16, Object Adapter -Structure
Oct, 16, Object Adapter F Applicability –You obtain a target class that you need to use in your designs, but, the public interface of the target class (it’s methods) does not match your requirements or it does not fit into the necessary class inheritance hierarchy. F Solution –Create an abstract interface ancestor class that implements the interchangeable interface that clients expect –Create an adapter subclass of the interface class –The constructor or other appropriate method in the adapter class will construct an instance of the target class (as appropriate). –Each method in the adapter class call the appropriate method(s) in the target class as needed to implement the expected functionality. F Consequences –Lets a single adapter work with many targets (e.g. the target and all it’s subclasses, if any). –Makes it harder to override the target’s behavior. The target must be subclassed and the adapter must be modified to use the subclass
Oct, 16, Bridge F Intent: Decouple an abstraction from its implementation so that the two can vary independently.
Oct, 16, Structure
Oct, 16, Implementation F Create an Implementation class which defines a public interface. F Create subclasses of the Implementation class to implement each operation as needed. F Create an Abstraction class which maintains an association to the Implementation class and provides a set of functions to invoke those operations. F For each client class that needs to use an Implementation subclass, subclass the client from the Abstraction.
Oct, 16, Consequences F Avoids permanent bindings between an abstraction and its implementation. F Both abstractions and implementations are extensible via subclassing. F Changes to the implementation have little or no impact on clients. F Hides implementation of an abstraction from clients. F Allows sharing an implementation among multiple objects and hiding that fact from clients.
Oct, 16, Composite -Object Structural F Intent: Compose objects into tree structures to represent whole-part hierarchies in a manner that lets clients treat objects and compositions uniformly. F Applicability –You want to represent whole-part hierarchies. –You don’t want clients to know the difference between compositions (nodes) and individual (leaf) objects
Oct, 16, Structure
Oct, 16, Implementation F Create an abstract Component class which defines the interface of all tree objects and implements default common behavior. F Subclass Component to create a concrete Composite class which implements behavior for storing and accessing child Component objects. F Subclass Component to create each individual child (leaf) object.
Oct, 16, Consequences F A near pure implementation of 1:N Recursive Connection, thus gains its advantages (and drawbacks, of course!) F Provides definitions of primitive class hierarchies that may easily be composed into recursive layers of more complex types with out affecting clients. This satisfies the Open/Closed principle nicely. F Clients code need not have any knowledge of the specific class of an object to call its operations methods on either individual objects or composites. (Liskov Substitution). However, this is not true for the Add, Remove and GetChild methods (see below). F May make a design overly general due to the difficulty of restricting Leaf objects. The public interface of Component makes this design almost like a Recursive Unification. F Design may violate Liskov Substitution due to possible client calls to the Add, Remove and GetChild methods for a Leaf object. If client calls these function in a leaf object, an error may result. Thus the client might need to implement special processing.
Oct, 16, Decorator -Object Structural F Intent: Attach additional responsibilities or alternate processing to an object dynamically. F Applicability: –You need to add or vary the responsibilities of an object based on wider system actions or changes –You need to easily remove a responsibility –When subclassing responsibilities would create an explosion of classes –Often used in GUIs to wrap visual “decorations” (scrollbars, frames, etc.) around windows and widgets
Oct, 16, Structure
Oct, 16, Consequences F Allows building flexible combinations and variations of responsibilities due to its strong basis on 1:1 Recursive Connection. F Client classes need not have any knowledge of a decorator’s specific operation to use it. (Liskov Substitution). F Separates public interface from implementation and moves code down and across a shallow inheritance hierarchy (Dependency Inversion) F Properties may added more than once, which may be bad or good, depending on requirements F If clients need to use a specific decorator’s interface, downcasting may be required, thus violating Liskov Substitution F Often results in systems with large numbers of small classes which seem to look alike. This can make it harder to find specific classes. Good documentation is required to explain the design (the design pattern simplifies this chore!)
Oct, 16, FAÇADE -Object Structural F Intent: Encapsulate a subsystem using a high-level interface, simplifying subsystem usage and hiding structural details.
Oct, 16, Implementation F Clients communicate with subsystem objects by calling methods in Façade F Clients never (or as seldom as possible) directly accessing objects in subsystem -- any such access weakens the encapsulation. F Subsystem objects usually retain no knowledge of client F Subsystem objects do not normally maintain any reference to Façade
Oct, 16, Structure
Oct, 16, Consequences F Eliminates hard to control tangled networks of object associations F Reduces number of objects clients need to interface with. F Promotes weak coupling, which enhances overall flexibility.
Oct, 16, PROXY -Object Structural F Intent: Provide a surrogate or place holder to control access to an object. F Implementation: –Create an abstract Subject class that defines the complete public interface of an object, but does not implement it. –Derive a RealSubject class from Subject and implement the public interface as needed to perform all required behavior. –Derive a ProxySubject which creates the RealSubject and passes all requests to it.
Oct, 16, Structure
Oct, 16, Consequences F Proxy is extremely good for patching inflexible OO designs in a well-controlled manner, often adding flexibility to the design. F Proxies can be used to distribute objects to different object spaces or across networks F ProxySubject can enhance RealSubject’s behavior -- particularly important when used to encapsulate 3rd party libraries.
Oct, 16, Flyweight F Intent: Use sharing to support large numbers of fine-grained object efficiently. F Applicability: –An application uses a large number of objects –Storage costs are high because of the sheer quantity of objects. –Most object state can be made extrinsic. –Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed. –The application doesn’t depend on object identity.
Oct, 16, Behavioral F Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects. F Behavioral patterns describe not just patterns of objects or classes but also the patterns of communication between them.
Oct, 16, Template Method F Intent –Let a descendant redefine certain tasks without modifying the basic algorithm defined by an ancestor method. F Solution –Break out primitive steps into separate methods in ancestor class. –Construct method for basic algorithm in ancestor that calls the primitive methods. –Override the primitive methods in descendant classes to implement specific tasks.
Oct, 16, Structure
Oct, 16, Consequences F A fundamental technique for code reuse -- particularly important in class libraries and frameworks to factor out common behavior. F Leads to inverted control structure called ‘Hollywood Principle’ (don’t call us, we’ll call you.) F A primitive method in the ancestor may provide a default behavior that descendants may optionally override (called hook methods.)
Oct, 16, Observer F Intent: –Define relationship between a group of objects such that whenever one object is updated all others are notified automatically. F Applicability –Changes to one object in a group requires changes to the others in the group –The number of objects in the group may vary –Loose coupling is desired between the objects in the group
Oct, 16, Structure
Oct, 16,
Oct, 16, Consequences F Subjects have limited knowledge of the objects in the observed group F Objects may easily be added or removed without changing existing objects F Update notifications are automatically broadcast to all interested objects F The cost of updating any object in the group may greater than expected F Update notifications may occur more frequently than desired or expected
Oct, 16, Mediator F Intent: define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. F Applicability: –A set of objects communicate in well-defined but complex ways. –Reusing an object is difficult because it refers to and communicates with many other objects. –A behavior that’s distributed between several classes should be customizable without a lot of subclassing.
Oct, 16,
Oct, 16, Consequences F It limits subclassing. F It decouples colleagues. F It simplifies object protocols. F It abstracts how objects cooperate. F It centralizes control.
Oct, 16, Chain of Responsibility F Intent: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. F Applicability: –More than one object may handle a request and the specific handler needs to be ascertained automatically –A request needs to be issued to a set objects that changes at run-time –You want to avoid any specific knowledge by the client of the available request handlers in the system F Implementation: Chain the receiver objects in a linked list and pass the request along the chain until an object handles it.
Oct, 16, Structure
Oct, 16, Consequences F Reduces coupling between a client and its responsibilities. New or alternate responsibilities can be easily added at runtime F Clients have no explicit knowledge of specific Receivers since it knows only an abstraction (Dependency Inversion Principle) F The abstract Receiver class is usually small, stable and not highly susceptible to change, thus it is “closed” (Open/Closed Principle) F There is no guarantee that any particular request may be actually handled, since it’s possible no handler in the chain can process it. F Clients are responsible to pass the request along the chain, calling each object in turn. If many clients exist, this will lead to code duplication and violates the Law of Demeter.
Oct, 16, COMMAND F Intent: Encapsulate a request as a parameterized object; allow different requests, queue or log requests and support undoable operations. F Applicability: –Parameterize objects by an action to perform. –Specify, queue, and execute requests at different times. –Support undo. –Support logging changes so that they can be reapplied in case of a system crash. –Structure a system around high-level operations built on primitives operations.
Oct, 16, Structure
Oct, 16,
Oct, 16, Consequences F Decouples an object from the operations performed on it. F Assemble commands into a composite command. F It’s easy to add new commands.
Oct, 16, State F Intent: allow an object to alter its behavior when its internal state changes. The object will appear to change its class. F Applicability: –An object’s behavior depends on its state, and it must change its behavior at run-time depending on that state. –Operations have large, multipart conditional statements that depend on the object’s state.
Oct, 16,
Oct, 16, Consequences F It localizes state-specific behavior and partitions behavior for different states. F It makes state transitions explicit. F State objects can be shared.
Oct, 16, Memento F Intent: without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later. F Applicability: –A snapshot of an object’s state must be saved so that it can be restored to that state later, and –A direct interface to obtaining the state would expose implementation details and break the object’s encapsulation.
Oct, 16,
Oct, 16, Consequences F Preserving encapsulation boundaries. F It simplifies originator. F Using mementos might be expensive. F Defining narrow and wide interfaces. F Hidden costs in caring for mementos.
Oct, 16, Strategy F Intent: define a family of algorithms, encapsulate each one, and make them interchangeable. F Applicability –Many related classes differ only in their behavior. –You need different variants of an algorithm. –An algorithm uses data that clients shouldn’t know about. –A class defines many behaviors, and these appear as multiple conditional statements in its operation.
Oct, 16,
Oct, 16, Consequences F Families of related algorithms. F An alternative to subclassing. F Strategies eliminate conditional statements. F A choice of implementations. F Clients must be aware of different strategies. F Communication overhead between strategy and context. F Increased number of objects.
Oct, 16, Visitor F Intent: represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. F Applicability: –An object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes. –Many distinct and unrelated operations need to perform on objects in an object structure. –The classes defining the object structure rarely change, but you often want to define new operations over the structure.
Oct, 16,
Oct, 16, Consequences F Visitor makes adding new operations easy. F A visitor gathers related operations and separates unrelated ones. F Adding new ConcreteElement classes is hard. F Visiting across class hierarchies. F Accumulating state. F Breaking encapsulation.
Oct, 16, Interpreter F Intent: given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. F Applicability: –The grammar is simple –Efficiency is not a critical concern
Oct, 16, Structure
Oct, 16, Consequences F It’s easy to change and extend the grammar. F Implementing the grammar is easy. F Complex grammars are hard to maintain. F Adding new ways to interpret expressions.
Oct, 16, Iterator F Intent: provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. F Applicability: –To access an aggregate object’s contents without exposing its internal representation. –To support multiple traversals of aggregate objects –To provide a uniform interface for traversing different aggregate structures (polymorphic iteration)
Oct, 16, Structure
Oct, 16, Consequences F It supports variations in the traversal of an aggregate. F Iterators simplify the Aggregate interface. F More than one traversal can be pending on an aggregate.