Factory Pattern PDF

Document Details

BravePulsar4522

Uploaded by BravePulsar4522

Karachi Institute of Economics and Technology

Tags

design patterns factory pattern object-oriented programming software engineering

Summary

This presentation introduces the Factory pattern, a crucial concept in object-oriented programming. It explains the "new" keyword's limitations concerning design principles. The examples emphasize "code-to-an-interface, " along with how factories can enhance code flexibility via design patterns.

Full Transcript

FACTORY PATTERN 1 LECTURE GOALS Cover Material from Chapters 3 of the Design Patterns Textbook Factory Pattern Factory Method Abstract Factory Pattern 2 THE PROBLEM WITH “NEW” Each...

FACTORY PATTERN 1 LECTURE GOALS Cover Material from Chapters 3 of the Design Patterns Textbook Factory Pattern Factory Method Abstract Factory Pattern 2 THE PROBLEM WITH “NEW” Each time we invoke the “new” command to create a new object, we violate the “Code to an Interface” design principle Example Duck duck = new DecoyDuck() Even though our variable’s type is set to an “interface”, in this case “Duck”, the class that contains this statement depends on “DecoyDuck” In addition, if you have code that checks a few variables and instantiates a particular type of class based on the state of those variables, if (hunting) { then the containing class depends on each referenced return newconcrete DecoyDuck()class Obvious Problems: needs to be recompiled each time a dep. changes } else { add new classes, change this code return new RubberDuck(); remove existing classes, change this code } This means that this code violates the open-closed principle and the “encapsulate what varies” design principle 3 PIZZA STORE EXAMPLE We have a pizza store program that wants to separate the process of creating a pizza with the process of preparing/ordering a pizza Initial Code: mixed the two processes 1 public class PizzaStore { 2 3 Pizza orderPizza(String type) { 4 5 Pizza pizza; 6 7 if (type.equals("cheese")) { 8 pizza = new CheesePizza(); Creation code has all the Creation 9 } else if (type.equals("greek")) { 10 pizza = new GreekPizza(); same problems as the 11 } else if (type.equals("pepperoni")) { code on the previous slide 12 pizza = new PepperoniPizza(); 13 } 14 15 pizza.prepare(); 16 17 pizza.bake(); pizza.cut(); Preparation 18 pizza.box(); 19 20 return pizza; 21 } 22 Note: excellent example of “coding to an interface” 23 } 24 4 ENCAPSULATE CREATION CODE A simple way to encapsulate this code is to put it in a separate class That new class depends on the concrete classes, but those dependencies no longer impact the preparation code 1 public class PizzaStore { 1 public class SimplePizzaFactory { 2 2 3 private SimplePizzaFactory factory; 3 public Pizza createPizza(String type) { 4 4 if (type.equals("cheese")) { 5 public PizzaStore(SimplePizzaFactory factory) { 5 return new CheesePizza(); 6 this.factory = factory; 6 } else if (type.equals("greek")) { 7 } 7 return new GreekPizza(); 8 8 } else if (type.equals("pepperoni")) { 9 public Pizza orderPizza(String type) { 9 return new PepperoniPizza(); 10 10 } 11 Pizza pizza = factory.createPizza(type); 11 } 12 12 13 pizza.prepare(); 13 14 pizza.bake(); } 15 pizza.cut(); 14 16 pizza.box(); 17 18 return pizza; 19 } 20 21 } 22 5 CLASS DIAGRAM OF NEW SOLUTION PIzzaStore Client factor SimplePizzaFactory y createPizza(): Pizza orderPizza( ): Pizza Factory Pizza Products prepare( ) bake() cut() box() CheesePizza VeggiePizza PepperoniPizza While this is nice, its not as flexible as it can be: to increase flexibility we need to look at two design patterns: Factory Method and Abstract Factory 6 FACTORY METHOD To 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 proclivities of the locals However, we want to retain the preparation process that has made PizzaStore such a great success The Factory Method Design Pattern allows you to do this by placing abstract, “code to an interface” code in a superclass placing object creation code in a subclass PizzaStore becomes an abstract class with an abstract createPizza() method 7 NEW PIZZASTORE CLASS FACTORY METHOD 1 public abstract class PizzaStore { 2 3 protected abstract createPizza(String type); THIS CLASS IS A (VERY SIMPLE) OO 4 FRAMEWORK. THE FRAMEWORK 5 public Pizza orderPizza(String type) { PROVIDES ONE SERVICE “PREPARE 6 PIZZA”. 7 Pizza pizza = createPizza(type); 8 THE FRAMEWORK INVOKES THE 9 pizza.prepare(); CREATEPIZZA() FACTORY METHOD TO 10 pizza.bake(); CREATE A PIZZA THAT IT CAN PREPARE 11 pizza.cut(); USING A WELL- DEFINED, CONSISTENT 12 pizza.box(); PROCESS. 13 14 return pizza; A “CLIENT” OF THE FRAMEWORK 15 } WILL SUBCLASS THIS CLASS AND 16 PROVIDE AN IMPLEMENTATION OF 17 } THE CREATEPIZZA() METHOD. 18 ANY DEPENDENCIES ON CONCRETE “PRODUCT” CLASSES ARE Beautiful Abstract Base Class! ENCAPSULATED IN THE SUBCLASS. 8 NEW YORK PIZZA STORE 1 public class NYPizzaStore extends PizzaStore { 2 public Pizza createPizza(String type) { 3 if (type.equals("cheese")) { 4 return new NYCheesePizza(); 5 } else if (type.equals("greek")) { 6 return new NYGreekPizza(); 7 } else if (type.equals("pepperoni")) { 8 return new NYPepperoniPizza(); 9 } 10 return null; 11 } 12 } 13 Nice and Simple. If you want a NY-Style Pizza, you create an instance of this class and call orderPizza() passing in the type. The subclass makes sure that the pizza is created using the correct style. If you need a different style, create a new subclass. 9 FACTORY METHOD: DEFINITION AND STRUCTURE The factory method design pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses Creator Product factoryMethod(): Product operation() ConcreteCreator ConcreteProduct factoryMethod(): ConcreteProduct Factory Method leads to the creation of parallel class hierarchies; ConcreteCreators produce instances of ConcreteProducts that are operated on by Creator’s via the Product interface 1 DEPENDENCY INVERSION PRINCIPLE Factory Method is one way of following the dependency inversion principle “Depend upon abstractions. Do not depend upon concrete classes.” Normally “high-level” classes depend on “low-level” classes; Instead, they BOTH should depend on an abstract interface DependentPizzaStore depends on eight concrete Pizza subclasses PizzaStore, however, depends on the Pizza interface as do the Pizza subclasses In this design, PizzaStore (the high-level class) no longer depends on the Pizza subclasses (the low level classes); they both depend on the abstraction “Pizza”. Nice. 1 DEPENDENCY INVERSION PRINCIPLE: HOW TO? To achieve the dependency inversion principle in your own designs, follow these GUIDELINES No variable should hold a reference to a concrete class No class should derive from a concrete class No method should override an implemented method of its base classes These are guidelines because if you were to blindly follow these instructions, you would never produce a system that could be compiled or executed Instead use them as instructions to help optimize your design And remember, not only should low-level classes depend on abstractions, but high-level classes should to… this is the very embodiment of “code to an interface” 1 DEMONSTRATIO N Lets look at some code The FactoryMethod directory of this lecture’s src.zip file contains an implementation of the pizza store using the factory method design pattern It even includes a file called “DependentPizzaStore.java” that shows how the code would be implemented without using this pattern DependentPizzaStore is dependent on 8 different concrete classes and 1 abstract interface (Pizza) PizzaStore is dependent on just the Pizza abstract interface (nice!) Each of its subclasses is only dependent on 4 concrete classes furthermore, they shield the superclass from these 1 MOVING ON The factory method approach to the pizza store is a big success allowing our company to create multiple franchises across the country quickly and easily But, bad news, we have learned that some of the franchises while following our procedures (the abstract code in PizzaStore forces them to) are skimping on ingredients in order to lower costs and increase margins Our company’s success has always been dependent on the use of fresh, quality ingredients so “Something Must Be Done!” ® 1 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 process Since different regions use different types of ingredients, we’ll 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, we’ll make sure that ingredients that meet our quality standards are used by all franchises They’ll have to come up with some other way to lower costs. ☺ 1 FIRST, WE NEED A FACTORY INTERFACE 1 public interface PizzaIngredientFactory { 2 3 public Dough createDough(); 4 public Sauce createSauce(); 5 public Cheese createCheese(); 6 public Veggies[] createVeggies(); 7 public Pepperoni createPepperoni(); 8 public Clams createClam(); 9 10 } 11 Note the introduction of more abstract classes: Dough, Sauce, Cheese, etc. 1 SECOND, WE IMPLEMENT A REGION-SPECIFIC FACTORY 1 PUBLIC CLASS CHICAGOPIZZAINGREDIENTFACTORY 2 IMPLEMENTS PIZZAINGREDIENTFACTORY This factory ensures that quality ingredients are used 3 { 4 during the pizza creation 5 public Dough createDough() 6 { return new process… 7 ThickCrustDough(); 8 } 9 public Sauce createSauce() 10 { return new 11 … while also taking into PlumTomatoSauce(); 12 } 13 account the tastes of people public Cheese createCheese() 14 { return new 15 who live in Chicago MozzarellaCheese(); 16 } 17 public Veggies[] createVeggies() { 18 Veggies veggies[] = { new BlackOlives(), 19 But how (or where) is new Spinach(), 20 new Eggplant() }; 21 this factory used? return veggies; 22 } 23 24 public Pepperoni createPepperoni() { 25 return new SlicedPepperoni(); 26 } 27 28 public Clams createClam() { 29 return new FrozenClams(); 17 30 } 31 } 32 WITHIN PIZZA SUBCLASSES… (I) 1 public abstract class Pizza { 2 String name; 3 4 Dough dough; 5 Sauce sauce; 6 Veggies veggies[]; 7 Cheese cheese; 8 Pepperoni pepperoni; 9 Clams clam; 10 11 abstract void prepare(); 12 13 void bake() { 14 System.out.println("Bake for 25 minutes at 350"); 15 } 16 17 void cut() { First, alter the Pizza abstract base class to make the prepare method abstract… 1 WITHIN PIZZA SUBCLASSES… (II) 1 public class CheesePizza extends Pizza 2 { PizzaIngredientFactory ingredientFactory; 3 4 public CheesePizza(PizzaIngredientFactory ingredientFactory) { 5 this.ingredientFactory = ingredientFactory; 6 } 7 8 void prepare() { 9 System.out.println("Preparing " + name); 10 dough = ingredientFactory.createDough(); 11 sauce = ingredientFactory.createSauce(); 12 cheese = ingredientFactory.createCheese(); 13 } 14 } 15 Then, update Pizza subclasses to make use of the factory! Note: we no longer need subclasses like NYCheesePizza and ChicagoCheesePizza because the ingredient factory now handles regional differences 1 ONE LAST STEP… Public class CHICAGOPIZZASTORE EXTENDS PIZZASTORE { protected Pizza createPizza(String item) { Pizza pizza = null; PizzaIngredientFactory ingredientFactory = new ChicagoPizzaIngredientFactory(); if (item.equals("cheese")) { pizza = new CheesePizza(ingredientFactory); pizza.setName("Chicago Style Cheese Pizza"); } else if (item.equals("veggie")) { pizza = new VeggiePizza(ingredientFactory); pizza.setName("Chicago Style Veggie Pizza"); … We need to update our PizzaStore subclasses to create the appropriate ingredient factory and pass it to each Pizza subclass in the createPizza factory method. 2 SUMMARY: WHAT DID WE JUST DO? 1. We created an ingredient factory interface to allow for the creation of a family of ingredients for a particular pizza 2. This abstract factory gives us an interface for creating a family of products 2.1.The factory interface decouples the client code from the actual factory implementations that produce context-specific sets of products 3. Our client code (PizzaStore) can then pick the factory appropriate to its region, plug it in, and get the correct style of pizza (Factory Method) with the correct set of ingredients (Abstract Factory) 2 ABSTRACT FACTORY: DEFINITION AND STRUCTURE The abstract factory design pattern provides an interface for creating families of related or dependent objects without specifying their AbstractFactory concrete classes «Interface» factor Client createProductA(): y AbstractProductA createProductB(): AbstractProductB ConcreteFactoryA ConcreteFactoryB createProductA(): createProductA(): ProductA1 ProductA2 createProductB(): createProductB(): ProductB1 ProductB2 AbstractProductA AbstractProductB «Interface» «Interface» ProductA1 ProductA2 ProductB1 ProductB2 2 WRAPPING UP All factories encapsulate object creation Simple Factory is not a bona fide design pattern but it is simple to understand and implement Factory Method relies on inheritance: object creation occurs in subclasses Abstract Factory relies on composition: object creation occurs in concrete factories Both can be used to shield your applications from concrete classes And both can aide you in applying the dependency inversion principle in your designs 2

Use Quizgecko on...
Browser
Browser