abstract factory abstract factory using factory method

Download Abstract Factory Abstract Factory using Factory Method

Post on 16-Jan-2016

219 views

Category:

Documents

0 download

Embed Size (px)

TRANSCRIPT

  • Abstract FactoryAbstract Factory using Factory Method

  • Factory Method*

  • Creating multiple factoriesNYPizzaFactoryChicagoPizzaFactory*

  • Creating Multiple FactoriesTo demonstrate the factory method pattern, the pizza store example evolves To include the notion of different franchises That exist in different parts of the country (California, New York, Chicago)Each franchise will need its own factory to create pizzas that match the tastes of the localsHowever, we want to retain the creation process that has made PizzaStore such a great successThe Factory Method Design Pattern allows you to do this byplacing abstract, code to an interface code in a superclassplacing object creation code in a subclassPizzaStore becomes an abstract class with an abstract createPizza() methodWe then create subclasses that override CreatePizza() for each region

    *

  • Changes in PizzaStorepublic abstract class PizzaStore { Pizza pizza = null; public abstract Pizza CreatePizza(String type);

    public void OrderPizza(String type) { pizza = CreatePizza(type); pizza.Prepare(); pizza.Bake(); pizza.Cut(); pizza.Box(); }//Method of Ordering a Pizza }*

  • Concrete Pizza Store Classespublic class NYPizzaStore : PizzaStore { public override Pizza CreatePizza(string type) { if (type.Equals("cheese")) { return new NYCheesePizza(); } else if (type.Equals("pepperoni")) {return new NYPepperoniPizza();} return null; } }public class ChicagoPizzaStore : PizzaStore {

    public override Pizza CreatePizza(String type) {

    if(type.Equals("cheese")) { return new ChicagoCheesePizza();} else if(type.Equals("pepperoni")) { return new ChicagoPepperoniPizza();} return null; } }*

  • Calling Program*class Program { static void Main(string[] args) { //Calling the NY Pizza Store to Order our Cheese Pizza PizzaStore nypizzastore = new NYPizzaStore(); nypizzastore.OrderPizza("cheese");

    Console.ReadLine(); } }

  • Allowing the subclasses to decideA factory method CreatePizza() handles object creation and encapsulates it in the subclass. This decouples the client code in the super class from the object creation that happens in the subclass.*

  • Pizza Store FranchisesCreator ClassesProduct Classes*

  • Looking at object dependenciesPizzaStoreNyStyleCheezePizzaNyStyleCheezePizzaNyStyleCheezePizzaNyStyleCheesePizzaChicagoCheezePizzaChicagoCheezePizzaChicagoCheezePizzaChicagoCheesePizzaBecause the Pizza Store depends on the concrete implementations any change in concrete classes may change the Pizza Store classBefore Applying Factory Method*

  • Design PrincipleDependency Inversion PrincipleDepend upon abstractions. Do not depend upon concrete classes.

    High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon details. Details should depend upon abstractions.

    *

  • Applying the principlePizzaStoreNyStyleCheezePizzaNyStyleCheezePizzaNyStyleCheezePizzaNyStyleCheesePizzaChicagoCheezePizzaChicagoCheezePizzaChicagoCheezePizzaChicagoCheesePizzaPizzaPizza is an abstract class*

  • Some guidelines to help with the principleTry and avoid having variables that refer to a concrete classInstead of using new use a factory to achieve thisTry and avoid deriving from a concrete classDerive from an abstract classTry and avoid overriding an implemented methodCould be done if deriving from an abstract class*

  • Moving OnThe factory method approach to the pizza store is a big success allowing our company to create multiple franchises across the country quickly and easilyBut, bad news, we have learned that some of the franchiseswhile following our procedures (the abstract code in PizzaStore forces them to)are skimping on ingredients in order to lower costs and increase marginsSo what can be done?

    *

  • Abstract Factory to the Rescue!We will alter our design such that a factory is used to supply the ingredients that are needed during the pizza creation processSince different regions use different types of ingredients, well create region-specific subclasses of the ingredient factory to ensure that the right ingredients are used But, even with region-specific requirements, since we are supplying the factories, well make sure that ingredients that meet our quality standards are used by all franchisesBut first let us look at what Abstract Factory Pattern is?

    *

  • IntentProvide an interface for creating families of related or dependent objects without specifying their concrete classesA.k.a KitThe Abstract Factory pattern is very similar to the Factory Method patternOne difference between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition Whereas the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation

    *

  • MotivationConsider a user interface that supports multiple look and feel standardsDifferent look and feel standards define different appearances and behaviors of user interface widgets like buttons, windows etc.The application should not hard code its widgets to a particular look and feelUsing objects of individual look and feel standards makes it hard to change the look and feel later.This problem can be solved by Abstract Widget Factory class, and abstract classes for each kind of widget.Concrete classes implement the widgets for a particular look and feel standard Also enforces dependencies between the concrete classes.

    *

  • Motivation (Contd)*

  • ApplicabilityUse the Abstract Factory pattern whenA system should be independent of how its products are created, composed and representedA system should be configured with one of multiple families of productsA 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.*

  • Structure*

  • ParticipantsAbstract Factory (WidgetFactory)Declares an interface for operations that create abstract product objectsConcrete Factory (MotifWidgetFactory, PMWidgetFactory)Implements the operations to create concrete product objectsAbstract Product (Window, Scrollbar, Button)Declares an interface for a type of product objectConcrete Product (MotifWindow, MotifScrollbar)Defines a product to be created by the corresponding concrete factory.Implements the AbstractProduct interface.Clientuses only interfaces declared by AbstractFactory and AbstractProduct classes.

    *

  • CollaborationsNormally a single instance of a ConcreteFactory class is created at run-time. (This is an example of the Singleton Pattern.) 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

    *

  • ConsequencesIsolates concrete classesFactory encapsulates the responsibility & process of creating product objectsMakes exchanging product families easyThe class of concrete factory appears only once in the application - that is , where its instantiatedPromotes consistency among productsEnforces, that products from one family are used together at one timeSupporting new kinds of products is difficultAbstractFactory interface fixes the set of products that can be createdInvolves changing AbstractFactory interface and all its subclasses.

    *

  • ImplementationFactories can be implemented as singletonsCreating the productsUse Factory Method patterndeclare FactoryMethod for each kind of product in AbstractFactoryoverride FactoryMethod in ConcreteFactoryUse Prototype pattern for ConcreteFactory if many product families are possibleinitialize the concrete factory with a prototypical instance of each product in the familyconcrete factory will create a new product by cloning the prototypeno need for a new concrete factory class for each new family*

  • Extending the factory patternNow we Expand the Pizza store exampleHow are you going to ensure that each franchise uses quality ingredientsWe are going to build factory of ingredients which is going to produce them and ship them to the franchises. How do we deal with families of ingredients?Chicago: ThickCrust Dough,PlumTomato Sauce,Raggiano Cheese and Dakin PepperoniNew York: ThinCrust Dough,Mariana Sauce,Mozzarella Cheese and Sliced PepperoniBasically, we have got same product families (Dough, Sauce, Cheese, Pepperoni) but different implementations based on region.*

  • Building the ingredient factoriesLets start by defining interface that is going to create all our ingredients

    public interface PizzaIngredientsFactory { Dough CreateDough(); Sauce CreateSauce(); Cheese CreateCheese(); Pepperoni CreatePepperoni(); }

    *

  • Building Individual Ingredient InterfacesDefining interfaces for individual ingredient

    /* Defining Interfaces for our Ingredients like * Dough,Sauce,Cheese,Pepperoni */ public interface Dough{string toString();} public interface Sauce{string toString();} public interface Cheese{string toString();} public interface Pepperoni{string toString();}*

  • Building NY ingredient factorypublic class NYPizzaIngredientsFactory : PizzaIngre