首页 > 其他 > 详细

第一章 简单工厂模式

时间:2016-03-29 23:53:25      阅读:211      评论:0      收藏:0      [点我收藏+]

面向对象编程永远在考虑:解藕和复用。

设计模式是前辈总结的结果,这些模式都是基于问题本身的抽象,活学活用才是王道。

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

简单工厂模式具有面向对象编程的基本优点:封装、继承和多态。

/**
 * Created by hero on 16-3-29.
 */
public abstract class Operation {
    private double numberA;
    private double numberB;

    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 abstract double getResult();
}
技术分享
/**
 * Created by hero on 16-3-29.
 */
public class OperationAdd extends Operation {

    @Override
    public double getResult() {
        return getNumberA() + getNumberB();
    }
}
View Code
技术分享
/**
 * Created by hero on 16-3-29.
 */
public class OperationSub extends Operation {
    @Override
    public double getResult() {
        return getNumberA() - getNumberB();
    }
}
View Code
/**
 * Created by hero on 16-3-29.
 */
public class OperationFactory {
    public static Operation getOperatioin(String op) {
        Operation operation = null;
        switch (op) {
            case "+":
                operation = new OperationAdd();
                break;
            case "-":
                operation = new OperationSub();
                break;
        }
        return operation;
    }
}
public class Main {

    public static void main(String[] args) {
        Operation operation = OperationFactory.getOperatioin("+");
        operation.setNumberA(1);
        operation.setNumberB(2);
        System.out.println(operation.getResult());
    }
}

 

第一章 简单工厂模式

原文:http://www.cnblogs.com/littlehoom/p/5335344.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!