笨鸟学飞

简单工厂模式

public class Main {
    public static void main(String[] args) {
        Factory factory = new Factory();
        Operation operation = factory.createOperate("+");
        operation.setNumberA(10);
        operation.setNumberB(5);
        System.out.println(operation.getResult());
    }
}
public class Factory{
    public Operation createOperate(String operate){
        switch (operate){
            case "+":
                return new Add();
            case "-":
                return new Sub();
        }
        return null;
    }
}
public abstract class Operation {
    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;
    }

    private double numberA = 0;
    private double numberB = 0;

    public abstract double getResult();
}

class Add extends Operation {

    @Override
    public double getResult() {
        return getNumberA() + getNumberB();
    }
}

class Sub extends Operation {

    @Override
    public double getResult() {
        return getNumberA() - getNumberB();
    }
}

根据传入参数由工厂决定创建哪一个实例

posted on 2016-05-28 14:17  笨鸟学飞  阅读(151)  评论(0编辑  收藏  举报

导航