码迷,mamicode.com
首页 > 其他好文 > 详细

简单工厂模式

时间:2016-05-28 15:41:02      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

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

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

简单工厂模式

标签:

原文地址:http://www.cnblogs.com/benniaoxuefei/p/5537319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!