Object-Oriented Oriented Programming Factory Method Pattern Abstract Factory Pattern CSIE Department, NTUT Woei-Kae Chen
Factory Method Pattern Factory Method Pattern Creational pattern
Factory Method: 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. Also known as Virtual Constructor
Factory Method: Motivation (1) Document Open() Close() Save() Revert() Framework for office applications Application CreateDocument() NewDocument() OpenDocument() Document* doc=createdocument(); docs.add(doc); doc->open(); Template Method Primitive operation Factory Method MyDocument MyApplication CreateDocument() return new MyDocument;
Factory Method: Motivation (2) GUI for Petri Net simulator Simulator GUIButton CreateNode() GraphNode AddPlace AddTransition AddLink Place Transition Link
Factory Method: Motivation (3) GUI for Logic simulator Dialog to modify the property of a device PropertyDialog Simulator device CreatePropertyDialog() orproperty andproperty CktProperty gateor gateand Circuit
Factory Method: 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.
Factory Method: Structure Client Product OR Creator FactoryMethod() AnOperation()... product = FactoryMethod();... ConcreteProduct ConcreteCreator FactoryMethod() Return new ConcreteProduct;
Factory Method: Participants Product (document) defines the interface of objects the factory method creates. ConcreteProduct (MyDocument) implements the product interface Creator (Application) declares the factory method, which returns an object of the product. Creator may also define a default implementation that returns a default ConcreteProduct object. may call the factory method to create a Product object. ConcreteCreator (MyApplication) overrides the factory method to return an instance of a ConcreteProduct.
Factory Method: Collaboration Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct.
Factory Method: Consequences (1) Benefit eliminates the need to bind application-specific classes into your code (client). client deals with the product interface, therefore it can work with any user-defined ConcreteProduct classes. Potential disadvantage clients might have to subclass the Creator class just to create a particular ConcreteProduct object. fine if the client has to subclass the Creator class anyway
Factory Method: Consequences (2) Provide hooks for subclasses the factory method is called only by Creators Creating objects with a factory method is always more flexible than creating an object directly. Factory Method gives subclasses a hook for providing an extended version of an object. Example: the Document class could define a factory method called CreateFileDialog for opening an existing document. Connects parallel class hierarchies Strategy client call factory method directly parallel class hierarchies result when a class delegates some of its responsibilities to a separate class
Factory Method: Consequences (3) Parallel class hierarchies example manipulation of graphical figures Figure CreateManipulator() Client Manipulator DownClick() Drag() UpClick() LineFigure TextFigure LineManipulator DownClick() Drag() UpClick() TextManipulator DownClick() Drag() UpClick()
Factory Method: Implementation (1) Two major varieties Creator does not provide an implementation for the factory method Creator provides a default implementation for the factory method designers of subclass can change the class of objects their parent class instantiates if necessary Parameterized factory methods create multiple kinds of products the factory method takes a parameter that identifies the kind of object to create the object share the Product interface
Factory Method: Implementation (2) Language-specific variants and issues C++ Factory methods are always virtual functions Factory methods are often pure virtual functions Creator s constructor can not call factory method they are not available yet. lazy initialization: access products solely through accessor operations constructor initialize concrete product as 0 accessor creates the product if it does not exist Naming conventions Use naming conventions to make it clear that you are using factory methods DoMakeClass() // Primitive operation+factory Method DoCreateXXX() // Primitive operation+factory Method
Factory Method: Implementation (3) Using templates to avoid subclassing class Creator { public: virtual Product * CreateProduct()=0; }; template <class TheProduct> class StandardCreator : public Creator { virtual Product * CreateProduct(); } template <class TheProduct> Product * StandardCreator<TheProduct>::CreateProduct() { return new TheProduct; }
Factory Method: Related Patterns Abstract Factory Abstract Factory is often implemented with factory methods. Template Method Factory methods are usually called within Template methods. Prototype Prototype and Abstract Factory are competing patterns. prototype storing objects in advance and clone them later factory method create objects by subclassing Client s view (difference) prototype often require an initialize operation factory method do not need an initialize operation Client s view (similarity) prototype creating itself factory method creating another concrete class object
Abstract Factory Pattern Abstract Factory Pattern Creational pattern
Abstract Factory: Intent Provide an interface for creating families of related or dependent objects without specifying their concrete classes. Also known as Kit
Abstract Factory: Motivation Multiple look-and-feel for Motif and Presentation Manager WidgetFactory CreateScrollBar() CreateWindow() Window Client MotifWidgetFactory CreateScrollBar() CreateWindow() PMWidgetFactory CreateScrollBar() CreateWindow() PMWindow ScrollBar MotifWindow PMScrollBar MotifScrollBar
Abstract Factory: Applicability Use the 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. a family of related product objects 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 interfaces, not their implementations.
Abstract Factory: Structure (1) AbstractFactory CreateProductA() CreateProductB() AbstractProductA Client ConcreteFactory1 CreateProductA() CreateProductB() ConcreteFactory2 CreateProductA() CreateProductB() ProductA2 ProductA1 AbstractProductB ProductB2 ProductB1
Abstract Factory: Structure (2) AbstractFactory CreateProductA() CreateProductB() AbstractProductA Client ConcreteFactory1 CreateProductA() CreateProductB() ConcreteFactory2 CreateProductA() CreateProductB() ProductA2 ProductA1 AbstractProductB Factory Method ProductB2 ProductB1
Abstract Factory: Participants AbstractFactory (WidgetFactory) declares an interface for operations that create abstract product objects. ConcreteFactory (PMWidgetFactory, etc.) implements the operations to create concrete product objects. AbstractProduct (Window, ScrollBar) declares an interface for a type of product object. ConcreteProduct (PMWindow, PMScrollBar) defines a product object to be created by the corresponding concrete factory. implements the AbstractProduct interface Client uses only interfaces declared by AbstractFactory and AbstractProduct classes.
Abstract Factory: Collaboration A single instance of a ConcreteFactory class is created (by client) at run-time. This ConcreteFactory is then used to create product objects for a particular implementation. To create different product objects, client should use a different concrete factory. Abstract Factory defers creation of product objects to its ConcreteFactory subclass.
Abstract Factory: Consequences Benefits It isolates concrete (product) classes (from clients) Product class names do not appear in the client code; they are isolated in the implementation of the concrete factory. It makes exchanging product families easy. Client can use different concrete product family simply by changing the concrete factory. It promotes consistency among products. Easy to enforce an application to use objects from only one family at a time. Liability Supporting new kinds of products is difficult To support a new kind of product, the factory interface must be extended changing AbstractFactory class and all its subclasses.
Abstract Factory: Implementation (1) Factories as Singletons An application typically needs only one instance of a ConcreteFactory. If a global point of access is required. Creating the products Using Factory Method pattern Define a factory method for each product requires a concrete factory subclass for each product family Using Prototype pattern If many product families are possible, the concrete factory can be implemented using Prototype pattern. Initialize concrete factory with a prototypical instance of each product in the family create a new product instance by cloning eliminates the need of subclassing for each product family.
Abstract Factory: Implementation (2) Defining extensible factories Usual design Define a different operation for each kind of product it can produce. Adding a new kind of product requires changing the AbstractFactory, ConcreteFactory, and all the classes that depend on it. A more flexible, but less safe design Add a parameter to operations that create objects. This parameter specifies the kind of product to be created. All products are returned to the client with the same abstract interface as given by the return type all product objects must have the same abstract base class.
Abstract Factory: Related Patterns Factory Method AbstractFactory classes are often implemented with factory methods. Prototype AbstractFactory classes can also be implemented using Prototype. Singleton A concrete factory is often a singleton.