head first 设计模式笔记4-工厂模式(简单工厂、工厂方法、抽象工厂)
1、简单工厂模式
Pizza
public abstract class Pizza { abstract void prepare(); abstract void bake(); abstract void cut(); abstract void box(); }
CheesePizza
public class CheesePizza extends Pizza { @Override void prepare() { } @Override void bake() { } @Override void cut() { } @Override void box() { } }
简单工厂:SimplePizzaFactory
/** * 简单工厂 * @author oy * @date 2019年9月1日 下午10:49:55 * @version 1.0.0 */ public class SimplePizzaFactory { public Pizza createPizza(String type) { Pizza pizza = null; if ("cheese".equals(type)) { pizza = new CheesePizza(); } else if ("pepperoni".equals(type)) { pizza = new PepperoniPizza(); } return pizza; } }
客户:使用工厂生产的对象
public class PizzaStore { SimplePizzaFactory factory; public PizzaStore(SimplePizzaFactory factory) { this.factory = factory; } public Pizza orderPizza(String type) { Pizza pizza = factory.createPizza(type); pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); return pizza; } }
2、工厂方法模式
工厂方法模式:工厂方法模式定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类
Animal
public abstract class Animal { public abstract void eat(); }
Animal实现类
public class Cat extends Animal { @Override public void eat() { System.out.println("猫吃鱼"); } } public class Dog extends Animal { @Override public void eat() { System.out.println("狗吃肉"); } }
工厂类
public interface Factory { public abstract Animal createAnimal(); }
public class CatFactory implements Factory { @Override public Animal createAnimal() { return new Cat(); } }
public class DogFactory implements Factory { @Override public Animal createAnimal() { return new Dog(); } }
测试代码
public static void main(String[] args) { // 需求:我要买只狗 Factory f = new DogFactory(); Animal a = f.createAnimal(); a.eat(); System.out.println("-------"); //需求:我要买只猫 f = new CatFactory(); a = f.createAnimal(); a.eat(); }
3、抽象工厂模式
posted on 2019-09-01 23:42 wenbin_ouyang 阅读(261) 评论(0) 编辑 收藏 举报