CS 210 Review Session October 5 th, 2006. Head First Design Patterns Chapter 4 Factory Pattern.

Slides:



Advertisements
Similar presentations
Creational Design Patterns. Creational DP: Abstracts the instantiation process Helps make a system independent of how objects are created, composed, represented.
Advertisements

Command Explained. Intent Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests,
Factory Pattern Building Complex Objects. New is an implementation  Calling “new” is certainly coding to an implementation  In fact, it’s always related.
Chapter 4: The Factory Pattern. Consider the Following Code Fragment Duck duck; if (picnic) { duck = new MallardDuck(); } else if (hunting) { duck = new.
CS 210 Introduction to Design Patterns September 19 th, 2006.
Command Pattern 1. Intent Encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log request,
Informatics 122 Software Design II Lecture 5 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
Brittany Johnson CSCI360 Abstract Factory Design Pattern.
. Plab – Tirgul 12 Design Patterns. Design Patterns u The De-Facto Book on Design Patterns:
Nov, 1, Design Patterns PROBLEM CONTEXT SOLUTION A design pattern documents a proven solution to a recurring problem in a specific context and its.
Software Design & Documentation – Design Pattern: Command Design Pattern: Command Christopher Lacey September 15, 2003.
Feb Ron McFadyen1 Adapter An adapter converts the interface of a class into another interface the client expects. An adapter lets classes work.
March Ron McFadyen1 Singleton pattern Singleton is designed to restrict instantiation of a class to one (or a few) objects. Useful when exactly.
PRESENTED BY SANGEETA MEHTA EECS810 UNIVERSITY OF KANSAS OCTOBER 2008 Design Patterns.
+ Informatics 122 Software Design II Lecture 8 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
CS 350 – Software Design Command Object Remote Control Object.
Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes.
Design Patterns.
CS 210 Introduction to Design Patterns September 28 th, 2006.
Design Pattern. The Observer Pattern The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all.
Tech Talk Go4 Factory Patterns Presented By: Matt Wilson.
CS 210 Introduction to Design Patterns September 7 th, 2006.
Software Components Creational Patterns.
Beware of bugs in the above code; I have only proved it correct, not tried it.
Abstract Factory Abstract Factory using Factory Method.
CS 210 Introduction to Design Patterns September 26 th, 2006.
Design Patterns Façade, Singleton, and Factory Methods Team Good Vibrations (1)
CS 210 Adapter Pattern October 19 th, Adapters in real life Page 236 – Head First Design Patterns.
Define an interface for creating an object, but let subclasses decide which class to instantiate Factory Method Pattern.
Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.
Define an interface for creating an object, but let subclasses decide which class to instantiate.
Creational Pattern: Factory Method At times, a framework is needed to standardize the behavior of objects that are used in a range of applications, while.
CS 590L – Distributed Component Architecture 02/20/2003Uttara Paingankar1 Design Patterns: Factory Method The factory method defines an interface for creating.
CS 415 N-Tier Application Development By Umair Ashraf June 22,2013 National University of Computer and Emerging Sciences Lecture # 3 Design Patterns (Observer,Factory,Singleton)
CS 210 Final Review November 28, CS 210 Adapter Pattern.
Using Software Design Patterns Bill Anderson. About me Fox developer since 1987 Fox developer since 1987 Program Director, Los Angeles Visual Foxpro Developers.
BEHAVIORAL PATTERNS 13-Sep-2012 Presenters Sanjeeb Kumar Nanda & Shankar Gogada.
The Factory Pattern Sanjay Yadav (ISE ).
Advanced Object-oriented Design Patterns Creational Design Patterns.
CSC 480 Software Engineering Design With Patterns.
CS 210 Review October 3, 2006.
Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another using Arrays. How does one work with these.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
Watching the movie the hard way…. Page 256 – Head First Design Patterns.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
Chapter 8 Object Design Reuse and Patterns. More Patterns Abstract Factory: Provide manufacturer independence Builder: Hide a complex creation process.
Pat’s Pizza creation Pizza orderPizza(String type){ Pizza pizza; if (type.equals(“cheese”)) { pizza = new CheesePizza(); } else if type.equals(“greek”))
StarBuzz Coffee Recipe Boil some water Brew coffee in boiling water Pour coffee in cup Add sugar and milk Tea Recipe Boil some water Steep tea in boiling.
Five Minute Design Patterns Doug Marttila Forest and the Trees May 30, 2009 Template Factory Singleton Iterator Adapter Façade Observer Command Strategy.
An object's behavior depends on its current state. Operations have large, multipart conditional statements that depend on the object's state.
CS 350 – Software Design The Decorator Pattern – Chapter 17 In this chapter we expand our e-commerce case study and learn how to use the Decorator Pattern.
Command Pattern Encapsulation Invocation. One size fits all.
Abstract Factory pattern Intent Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Overview of Behavioral Patterns ©SoftMoore ConsultingSlide 1.
SE 461 Software Patterns. ABSTRACT FACTORY PATTERN.
SE 461 Software Patterns. FACTORY METHOD PATTERN.
CS 210 Introduction to Design Patterns September 14 th, 2006.
Command Pattern. Intent encapsulate a request as an object  can parameterize clients with different requests, queue or log requests, support undoable.
Design Patterns: MORE Examples
Chapter 10 Design Patterns.
Design Pattern Catalogues
Factory Patterns 1.
Programming Design Patterns
Command Pattern 1.
Programming Design Patterns
Software Engineering Lecture 7 - Design Patterns
Abstract Factory Pattern
PH Chapter 3 Thanks for the Memory Leaks Pushme-Pullyu (pp
ADAPTER FAÇADE FACTORY OBSERVER SINGLETON STRATEGY
CSC 480 Software Engineering
Presentation transcript:

CS 210 Review Session October 5 th, 2006

Head First Design Patterns Chapter 4 Factory Pattern

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() }

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.

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

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

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; }

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; }

Complete example for Simple Factory SimplePizzaFactory factory = new SimplePizzaFactory(); PizzaStore store = new PizzaStore(factory); Pizza pizza = store.orderPizza("cheese");

Simple Factory Defined PizzaStore orderPizza() SimplePizzaFactory createPizza() Pizza prepare() bake() cut() box() CheesePizza VeggiePizza ClamPizza

Creating multiple factories PizzaStore NYPizzaFactory ChicagoPizzaFactory

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");

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; }

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.

Factory Method Pattern PizzaStore createPizza() orderPizza() NYStylePizzaStore createPizza() ChicagoStylePizzaStore createPizza() PizzaNYStyleCheesePizza ChStyleCheesePizza Creator Classes Product Classes

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.

Factory Method Pattern Defined Product ConcreteProduct ConcreteCreator factoryMethod() Creator factoryMethod() anOperation()

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

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]

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

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

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

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(); }

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(); }

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 }

Abstract Factory Pattern defined The abstract factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.

ProductA1 Abstract Factory Pattern > AbstractFactory CreateProductA() CreateProductB() ConcreteFactory1 CreateProductA() CreateProductB() ConcreteFactory2 CreateProductA() CreateProductB() Client > AbstractProdcutA ProductA1 > AbstractProdcutB ConcreteFactory1 CreateProductA() CreateProductB() ProductB1 ProductA2 ProductB2

ProductA1 Abstract Factory Pattern example > PizzaIngFactory CreateDough() CreateCheese() ConcreteFactory1 CreateProductA() CreateProductB() ChicPizzaIngFctry CreateDough() CreateCheese() Pizza > Dough ThinCrust > Cheese NYPizzaIngFctry CreateDougn() CreateCheese() Reggiano ThickCrust Mozzarella

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.

Head First Design Patterns Chapter 6 Command Pattern Encapsulating Invocation

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

Introducing the command pattern Create Command Object execute()setCommandexecute() action1 action2 creatCommandObject() setCommand() execute() action_X()

Command Pattern for home automation action() execute(){ receiver.action() } execute() An encapsulated Request Invoker

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.

Command Pattern Class Diagram ClientInvoker setCommand() > Command execute() undo() Receiver action() ConcreteCommand execute() undo()

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()

Command pattern – Undo operation Eclipse code review

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(); }

Macro Command – Party mode Eclipse code review

Page 228 – Head First Design Patterns

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.

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.