Presentation is loading. Please wait.

Presentation is loading. Please wait.

Design Pattern Catalogues

Similar presentations


Presentation on theme: "Design Pattern Catalogues"— Presentation transcript:

1 Design Pattern Catalogues
GoF (“the gang of four”) catalogue “Design Patterns: Elements of Reusable Object-Oriented Software,” Gamma, Helm, Johnson, Vlissides, Addison-Wesley, 1995 POSA catalogue Pattern-Oriented Software Architecture, Buschmann, et al.; Wiley, 1996

2 Classification of GoF Design Pattern
Creational Structural Behavioral Factory Method Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Flyweight Facade Proxy Interpreter Template Method Chain of Responsibility Command Iterator Mediator Memento Observer State Strategy Visitor

3 What are creational patterns?
Design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation Make a system independent of the way in which objects are created, composed and represented Recurring themes: Encapsulate knowledge about which concrete classes the system uses (so we can change them easily later) Hide how instances of these classes are created and put together (so we can change it easily later)

4 Benefits of creational patterns
Creational patterns let you program to an interface defined by an abstract class That lets you configure a system with “product” objects that vary widely in structure and functionality Example: GUI systems InterViews GUI class library Multiple look-and-feels Abstract Factories for different screen components

5 Benefits of creational patterns
Generic instantiation – Objects are instantiated without having to identify a specific class type in client code (Abstract Factory, Factory) Simplicity – Make instantiation easier: callers do not have to write long complex code to instantiate and set up an object (Builder, Prototype pattern) Creation constraints – Creational patterns can put bounds on who can create objects, how they are created, and when they are created

6 Abstract Factory (Creational)
Intent Create families of related objects without specifying class names Applicability When clients cannot anticipate groups of classes to instantiate © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

7 Abstract Factory (Cont'd)
Structure «instantiate» «instantiate» © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley «instantiate» «instantiate»

8 Abstract Factory: Participants
AbstractFactory Declares an interface for operations that create abstract products ConcreteFactory Implements the operations to create concrete product objects: usually instantiated as a Singleton AbstractProduct Declares an interface for a type of product object; Concrete Factories produce the concrete products ConcreteProduct Defines a product object to be created by the corresponding concrete factory

9 Abstract Factory: Applicability
Use Abstract Factory 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 You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations

10 Abstract Factory: Consequences
Good: Isolates concrete classes All manipulation on client-side done through abstract interfaces Makes exchanging product families easy Just change the ConcreteFactory Enforces consistency among products Bad Supporting new kinds of products is difficult Have to reprogram Abstract Factory and all subclasses But it’s not so bad in dynamically typed languages

11 Abstract Factory: Implementation
Usually should be a Singleton Define a Factory Method (GoF) in AbstractFactory – ConcreteFactory then specifies its products by overriding the factory for each public class USAddressFactory implements AddressFactory{ public Address createAddress(){ return new USAddress(); } public PhoneNumber createPhoneNumber(){ return new USPhoneNumber(); Maybe use Prototype pattern in dynamically typed languages (e.g. Smalltalk) to simplify creation

12 Abstract Factory (Cont'd)
Consequences Flexibility: removes type dependencies from clients Abstraction: hides product's composition Hard to extend factory interface to create new products Implementation Parameterization as a way of controlling interface size Configuration with Prototypes Known Uses InterViews Kits ET++ WindowSystem

13 Conclusions Abstract Factory:
Lets you choose what family of products to create at runtime Isolates the implementation from clients, since clients only use the interfaces Makes exchanging product families simple

14 Builder

15 Builder

16 Builder

17 Builder

18 Builder: Overview Intent Think of a car factory
Separate the construction of a complex object from its representation so that the same construction process can create different representations Think of a car factory Boss tells workers (or robots) to build each part of a car Workers build each part and add them to the car being constructed

19 Builder: Participants
Builder Specifies an abstract interface for creating parts of a Product object ConcreteBuilder Constructs and assembles parts of the product by implementing the Builder interface Director Constructs an object using the Builder interface Product Represents the complex object under construction Includes classes that define the constituent parts Gives interfaces for assem- bling the parts Builder: The abstract class of all workers Concrete Builder: A specific worker Director: The boss Product: The car

20 Builder: Collaborations
Client creates Director object and configures it with a Builder Director notifies Builder to build each part of the product Builder handles requests from Director and adds parts to the product Client retrieves product from the Builder

21 Builder: Applicability
Use Builder when: The algorithm for creating a complex object should be independent of the parts that make up the object and how they’re assembled The construction process must allow different representations for the object being constructed The building process can be broken down into discrete steps (difference between Builder and Abstract Factory)

22 Builder: Consequences
Lets you vary a product’s internal representation by using different Builders Isolates code for construction and representation Gives finer-grain control over the construction process

23 Builder: Implementation
Issues to consider: Assembly and construction interface: generality Is an abstract class for all Products necessary? Usually products don’t have a common interface Usually there’s an abstract Builder class that defines an operation for each component that a director may ask it to create. These operations do nothing by default (empty, non-virtual methods in C++) The ConcreteBuilder overrides operations selectively

24 Conclusions Builder: Lets you vary how a product gets assembled.
Can define a new kind of builder for a product to assemble it in a different way Client doesn’t need to know anything about the construction process, nor the parts that make up a product.

25 FACTORY METHOD (Class Creational)
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.

26 FACTORY METHOD (Class Creational)
Motivation: Framework use abstract classes to define and maintain relationships between objects Framework has to create objects as well - must instantiate classes but only knows about abstract classes - which it cannot instantiate Factory method encapsulates knowledge of which subclass to create - moves this knowledge out of the framework

27 Factory Method Structure
... product = FactoryMethod() return new ConcreteProduct

28 FACTORY METHOD Motivation
docs Document Application Open() Close() Save() Revert() CreateDocument() NewDocument() OpenDocument() Document* doc=CreateDocument(); docs.Add(doc); doc->Open(); MyApplication MyDocument return new MyDocument CreateDocument()

29 Applicability Use the Factory Method pattern when
a class can´t anticipate the class of objects it must create. a class wants its subclasses to specify the objects it creates. classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

30 Participants Product Defines the interface of objects the factory method creates ConcreteProduct Implements the product interface Creator Declares the factory method which returns object of type product May contain a default implementation of the factory method Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate Concrete Product. ConcreteCreator Overrides factory method to return instance of ConcreteProduct

31 Factory Pattern Example Car Factory produces different Car objects
Original Different classes implement Car interface Directly instantiate car objects Need to modify client to change cars Using pattern Use carFactory class to produce car objects Can change cars by changing carFactory

32 Factory Example class 350Z implements Car; // fast car
class Ram implements Car; // truck class Accord implements Car; // family car Car fast = new 350Z(); // returns fast car public class carFactory { public static Car create(String type) { if (type.equals("fast")) return new 350Z(); if (type.equals("truck")) return new Ram(); else if (type.equals(“family”) return new Accord(); } Car fast = carFactory.create("fast"); // returns fast car

33 Example Suppose that you are required to develop a
system that accepts orders for pizzas. There are three types of pizzas, namely, cheese, Greek, and pepperoni. The pizzas differ according to the dough used, the sauce used and the toppings. Draw a class diagram for the system.

34 Example:Class Diagram
Problems with the design

35 Example: Revised System
Suppose that the Greek pizza is not popular and must be removed and two new pizzas, Clam and Veggie, must be added to the menu. Programming to implementation like makes such changes difficult. Creating a SimpleFactory to encapsulate the code that changes will make the design more flexible. Remove the code that creates a pizza – forms a factory.

36 Example: Revised Class Diagram

37 Example: 2nd System Revision
Franchises in different parts of the country are now adding their own special touches to the pizza. For example, customers at the franchise in New York like a thin base, with tasty sauce and little cheese. However, customers in Chicago prefer a thick base, rich sauce and a lot of cheese. Some franchises also cut the pizza slices differently (e.g. square) You need to extend the system to cater for this.

38 Creator Class

39 Product Class

40 In Summary The creator gives you an interface for writing objects.
The creator specifies the “factory method”, e.g. the createPizza method. Other methods generally included in the creator are methods that operate on the product produced by the creator, e.g. orderPizza. Only subclasses implement the factory method.

41 In summary (contd.) When you have code that instantiates concrete classes that may change, encapsulate the code that changes. The factory pattern allows you to encapsulate the behaviour of the instantiation. Duplication of code is prevented. Client code is decoupled from actual implementations. Programming to interface not implementation.

42 Singleton (Creational)
Intent Ensure a class only ever has one instance, and provide a global point of access to it. Applicability When there must be exactly one instance of a class, and it must be accessible 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 © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

43 Singleton (cont'd) Structure
© E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

44 return uniquelnstance static Instance() SingletonOperation()
GetSingletonData() Static uniquelnstance singletonData

45 Singleton Example public class Employee {
public static final int ID = 1234; // ID is a singleton } public final class MySingleton { // declare the unique instance of the class private static MySingleton uniq = new MySingleton(); // private constructor only accessed from this class private MySingleton() { … } // return reference to unique instance of class public static MySingleton getInstance() { return uniq;

46 Singleton (cont'd) Consequences Implementation
Reduces namespace pollution Makes it easy to change your mind and allow more than one instance Allow extension by subclassing Same drawbacks of a global if misused Implementation may be less efficient than a global Concurrency pitfalls Implementation Static instance operation Registering the singleton instance © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

47 Singleton (cont'd) Known Uses Unidraw's Unidraw object
Smalltalk-80 ChangeSet, the set of changes to code InterViews Session object © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

48 Conclusions Creational design patterns are beneficial in that they allow your software to tightly control the way in which it constructs objects Separate users of the code from the messy details of creating and building objects

49 Prototype A fully initialized instance to be copied or cloned
Definition - Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.

50 Prototype Pattern

51 Roles and Responsibilities


Download ppt "Design Pattern Catalogues"

Similar presentations


Ads by Google