当前位置:
文档之家› 创建型设计模式 培训(英文)
创建型设计模式 培训(英文)
Simple Pattern
public class PizzaStore { Pizza orderPizza(String type) { Pizza pizza = null; if(type.equals("chees")) { 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(); return pizza; } }
Simple Pattern
Feature
Hale Waihona Puke Fade Format
you don't need to instantiate an object to make use of the create method you can't create sublcass and change the behavior of the create method Not typical design pattern-- more of a programming idiom
Factory Pattern
Simple Factory
Simply moved the code that is used to create object to a new class Creator.
Factory Pattern
Pizza Story
You want to open a pizza store, Assume that you organize like this:
™
Common & Difference of Design Pattern
Creational Pattern and Refactor
Bryan Li 6/18/2007
Agenda
OO Design Principle
Design Pattern
OCP(Open-Closed Principle) LSP(Liskov Substitution Principle) SRP(single responsibility Principle) DIP(Dependence Inversion Principle) ISP(Interface Segregation Principle) CARP(Composite/Aggregate Reuse Principle) LoD(Las od Demeter—Least Knowledge PrincipleLKP)
Simple Pattern
Mending design of pizza story
Simple Pattern
public class SimplePizzaFactory { public static Pizza createPizza(String type) { Pizza pizza = null; if (type.equals("chees")) { pizza = new CheesePizza(); } else if (type.equals("greek")) { pizza = new GreekPizza(); } else if (type.equals("pepperoni")) { pizza = new PepperoniPizza(); } return pizza; } }
Merge Creator into ConcreteProduct
Simple Pattern
Advantage
Disadvantage
Reuse the code that create object
If product has any change, Creator class should be impacted. OCP: if add new type of product, in the view of client and product, it conform to OCP, but in the view of Factory Creator, it does not.
Factory Method
Pizza Story
Because your pizza store has a good business, many people want to open your sub store in New York and Chicago. So you will the localize favor problem. Based on simple factory, design like the following:
OO Design Principle
Factory Method
Define an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Creational Pattern Structural Pattern Behavioral Pattern
Agenda
Creational Pattern
Factory Pattern
Simple Factory Factory Method Abstract Factory
Add SimplePizzaFactory Class
public class PizzaStore { SimplePizzaFactory factory; public Pizza orderPizza(String type) { Pizza pizza = SimplePizzaFactory.createPizza(type); pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); return pizza; } }