Download presentation
Presentation is loading. Please wait.
Published byRegina Arnold Modified over 9 years ago
1
CS 210 Review Session October 5 th, 2006
2
Head First Design Patterns Chapter 4 Factory Pattern
3
Pizza creation Pizza orderPizza(String type){ if (type.equals(“cheese”)) { pizza = new CheesePizza(); } else if type.equals(“greek”)) { pizza = new GreekPizza(); } else if type.equals(“pepperoni”)) { pizza = new PepperoniPizza(); } pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box() }
4
Identifying the aspects that vary If the pizza shop decides to change the types of pizza it offers, the orderPizza method has to be changed.
5
Pizza example Pizza orderPizza(String type){ if (type.equals(“cheese”)) { pizza = new CheesePizza(); } else if type.equals(“greek”)) { pizza = new GreekPizza(); } else if type.equals(“pepperoni”)) { pizza = new PepperoniPizza(); } pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box() } Part that varies. Part that remains constant
6
Encapsulating object creation if (type.equals(“cheese”)) { pizza = new CheesePizza(); } else if type.equals(“greek”)) { pizza = new GreekPizza(); } else if type.equals(“pepperoni”)) { pizza = new PepperoniPizza(); } SimplePizzaFactory
7
Building a simple pizza factory public class SimplePizzaFactory { public Pizza createPizza(String type) { Pizza pizza = null; if (type.equals("cheese")) { pizza = new CheesePizza(); } else if (type.equals("pepperoni")) { pizza = new PepperoniPizza(); } else if (type.equals("clam")) { pizza = new ClamPizza(); } else if (type.equals("veggie")) { pizza = new VeggiePizza(); } return pizza; }
8
Reworking the PizzaStore Class public class PizzaStore { SimplePizzaFactory factory; public PizzaStore(SimplePizzaFactory factory) { this.factory = factory; } public Pizza orderPizza(String type) { Pizza pizza; pizza = factory.createPizza(type); pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); return pizza; }
9
Complete example for Simple Factory SimplePizzaFactory factory = new SimplePizzaFactory(); PizzaStore store = new PizzaStore(factory); Pizza pizza = store.orderPizza("cheese");
10
Simple Factory Defined PizzaStore orderPizza() SimplePizzaFactory createPizza() Pizza prepare() bake() cut() box() CheesePizza VeggiePizza ClamPizza
11
Creating multiple factories PizzaStore NYPizzaFactory ChicagoPizzaFactory
12
Creating multiple instances NYPizzaFactory nyFactory = new NYPizzaFactory(); PizzaStore nyStore = new PizzaStore(nyFactory); Pizza pizza = nyStore.orderPizza("cheese"); ChicagoPizzaFactory chicagoFactory = new ChicagoPizzaFactory(); PizzaStore chicagoStore = new PizzaStore(chicagoFactory); Pizza pizza = chicagoStore.orderPizza("cheese");
13
Alternate approach – Abstract method – a framework for the pizza store public abstract class PizzaStore { abstract Pizza createPizza(String item); public Pizza orderPizza(String type) { Pizza pizza = createPizza(type); pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); return pizza; }
14
Allowing the subclasses to decide PizzaStore createPizza() orderPizza() NYStylePizzaStore createPizza() ChicagoStylePizzaStore createPizza() A factory method 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.
15
Factory Method Pattern PizzaStore createPizza() orderPizza() NYStylePizzaStore createPizza() ChicagoStylePizzaStore createPizza() PizzaNYStyleCheesePizza ChStyleCheesePizza Creator Classes Product Classes
16
Factory Method Pattern defined The factory method pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclass.
17
Factory Method Pattern Defined Product ConcreteProduct ConcreteCreator factoryMethod() Creator factoryMethod() anOperation()
18
Looking at object dependencies Pizza Store NyStyle Cheeze Pizza NyStyle Cheeze Pizza NyStyle Cheeze Pizza NyStyle Clam Pizza Chicago Cheeze Pizza Chicago Cheeze Pizza Chicago Cheeze Pizza Chicago Clam Pizza
19
Design Principle Dependency Inversion Principle Depend 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.” [The Dependency Inversion Principle has been proposed by Robert C. Martin]
20
Applying the principle Pizza Store NyStyle Cheeze Pizza NyStyle Cheeze Pizza NyStyle Cheeze Pizza NyStyle Clam Pizza Chicago Cheeze Pizza Chicago Cheeze Pizza Chicago Cheeze Pizza Chicago Clam Pizza Pizza is an abstract class
21
Some guidelines to help with the principle Try and avoid having variables that refer to a concrete class Try and avoid deriving from a concrete class Try and avoid overriding an implemented method
22
Extending the factory pattern… Expanding the Pizza store example How do we deal with families of ingredients? Chicago: FrozenClams, PlumTomatoSauce, ThickCrustDough, MozzarellaCheese New York: FreshClams, MarinaroSauce, ThinCrustDough, ReggianoCheese California: Calamari, BruuuschettaSauce, VeryThinCrust, GoatCheese
23
Building the ingredient factories public interface PizzaIngredientFactory { public Dough createDough(); public Sauce createSauce(); public Cheese createCheese(); public Veggies[] createVeggies(); public Pepperoni createPepperoni(); public Clams createClam(); }
24
Building NY ingredient factory public class NYPizzaIngredientFactory implements PizzaIngredientFactory { public Dough createDough() { return new ThinCrustDough(); } public Sauce createSauce() { return new MarinaraSauce(); } public Cheese createCheese() { return new ReggianoCheese(); } public Veggies[] createVeggies() { Veggies veggies[] = { new Garlic(), new Onion(), new Mushroom(), new RedPepper() }; return veggies; } public Pepperoni createPepperoni() { return new SlicedPepperoni(); } public Clams createClam() { return new FreshClams(); }
25
Reworking the pizzas public abstract class Pizza { String name; Dough dough; Sauce sauce; Veggies veggies[]; Cheese cheese; Pepperoni pepperoni; Clams clam; abstract void prepare(); void bake() { System.out.println("Bake for 25 minutes at 350"); } void cut() { System.out.println("Cutting the pizza into diagonal slices"); } void box() { System.out.println("Place pizza in official PizzaStore box"); } void setName(String name) { this.name = name; } String getName() { return name; } public String toString() { \\ code to print pizza here }
26
Abstract Factory Pattern defined The abstract factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.
27
ProductA1 Abstract Factory Pattern > AbstractFactory CreateProductA() CreateProductB() ConcreteFactory1 CreateProductA() CreateProductB() ConcreteFactory2 CreateProductA() CreateProductB() Client > AbstractProdcutA ProductA1 > AbstractProdcutB ConcreteFactory1 CreateProductA() CreateProductB() ProductB1 ProductA2 ProductB2
28
ProductA1 Abstract Factory Pattern example > PizzaIngFactory CreateDough() CreateCheese() ConcreteFactory1 CreateProductA() CreateProductB() ChicPizzaIngFctry CreateDough() CreateCheese() Pizza > Dough ThinCrust > Cheese NYPizzaIngFctry CreateDougn() CreateCheese() Reggiano ThickCrust Mozzarella
29
Summary so far.. OO Basics Abstraction Encapsulation Inheritance Polymorphism OO Principles Encapsulate what varies Favor composition over inheritance Program to interfaces not to implementations Strive for loosely coupled designs between objects that interact Classes should be open for extension but closed for modification. Depend on abstracts. Do not depend on concrete classes. OO Patterns Strategy Pattern defines a family of algorithms, Encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. Decorator Pattern – attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative for sub-classing for extending functionality Abstractor Factory – Provide an interface for creating families of related or dependent objects without specifying their concrete classes. Factory Method – Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to the subclasses.
30
Head First Design Patterns Chapter 6 Command Pattern Encapsulating Invocation
31
Motivating problem description Build a remote that will control variety of home devices Sample devices: lights, stereo, TV, ceiling light, thermostat, sprinkler, hot tub, garden light, ceiling fan, garage door
32
Introducing the command pattern Create Command Object execute()setCommandexecute() action1 action2 creatCommandObject() setCommand() execute() action_X()
33
Command Pattern for home automation action() execute(){ receiver.action() } execute() An encapsulated Request Invoker
34
Command Pattern defined The Command Pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.
35
Command Pattern Class Diagram ClientInvoker setCommand() > Command execute() undo() Receiver action() ConcreteCommand execute() undo()
36
Command Pattern Class Diagram for Home automation RemoteLoader RemoteControl onCommands offCommands setCommand() onButtonPushed() offButtonPushed() > Command execute() undo() Light on() off() LightOnCommand execute() undo() LightOffCommand execute() undo()
37
Command pattern – Undo operation Eclipse code review
38
Macro Commands – Party mode public class MacroCommand implements Command { Command[] commands; public MacroCommand(Command[] commands) { this.commands = commands; } public void execute() { for (int i = 0; i < commands.length; i++) { commands[i].execute(); } public void undo() { for (int i = 0; i < commands.length; i++) { commands[i].undo(); }
39
Macro Command – Party mode Eclipse code review
40
Page 228 – Head First Design Patterns
42
Summary so far.. OO Basics Abstraction Encapsulation Inheritance Polymorphism OO Principles Encapsulate what varies Favor composition over inheritance Program to interfaces not to implementations Strive for loosely coupled designs between objects that interact Classes should be open for extension but closed for modification. Depend on abstracts. Do not depend on concrete classes.
43
Summary so far… OO Patterns Strategy Pattern defines a family of algorithms, Encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. Decorator Pattern – attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative for sub-classing for extending functionality Abstractor Factory – Provide an interface for creating families of related or dependent objects without specifying their concrete classes. Factory Method – Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to the subclasses. Command Pattern – Encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.