设计模式之工厂模式
工厂模式有三种:
简单工厂模式
工厂模式
抽象工厂模式
简单工厂模式
使用静态方法,通过接受参数的不同来返回不同的对象实例。
Operation 和 它的四个子类:
/** * 操作类,所有 二元运算 的顶层父类 */ class Operation { private double numberA = 0; private double numberB = 0; public double getNumberA() { return numberA; } public void setNumberA(double numberA) { this.numberA = numberA; } public double getNumberB() { return numberB; } public void setNumberB(double numberB) { this.numberB = numberB; } // 每个子类都会重写这个方法,以使用子类计算的逻辑 public double getResult() { double result = 0; return result; } } /* * 加减乘除 四个子类 */ class OperationAdd extends Operation { @Override public double getResult() { return getNumberA() + getNumberB(); } } class OperationSub extends Operation { @Override public double getResult() { return getNumberA() - getNumberB(); } } class OperationMul extends Operation { @Override public double getResult() { return getNumberA() * getNumberB(); } } class OperationDiv extends Operation { @Override public double getResult() { return getNumberA() / getNumberB(); } }
OperationFactory 工厂类:
/** * 简单运算工厂类 */ class OperationFactory{ public static Operation createOperate(String operate) { Operation oper = null; switch(operate) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; case "*": oper = new OperationMul(); break; case "/": oper = new OperationDiv(); break; } return oper; } }
工厂模式
每一种产品提供一个工厂类。通过不同的工厂实例来创建不同的产品实例。
Factory 和 Product 顶层抽象类:
public abstract class Product { public abstract void use(); } public abstract class Factory { // 该 create 方法使用到了 Template Method Pattern public final Product create(String owner) { Product p = createProduct(owner); registerProduct(p); return p; } protected abstract Product createProduct(String owner); protected abstract void registerProduct(Product product); }
不同的产品,使用不同的工厂实例:
public class IDCard extends Product{ private String owner; IDCard(String owner) { System.out.println("建立" + owner + "的卡。"); this.owner = owner; } public void use() { System.out.println("使用" + owner + "的卡。"); } public String getOwner() { return owner; } } public class IDCardFactory extends Factory { private Vector owners = new Vector(); protected Product createProduct(String owner) { return new IDCard(owner); } protected void registerProduct(Product product) { owners.add(((IDCard)product).getOwner()); } public Vector getOwners() { return owners; } }