【设计模式系列学习笔记】1、简单工厂模式

如果说数学是思维的体操,那设计模式就是面向对象编程思维的体操;

简易计算器类结构图:

操作类,定义两个操作数,并声明抽象方法getResult(),具体实现由子类完成;

public abstract class Operation {

    private double numberA;

    private double numberB;

    public abstract double getResult() throws Exception;

}

加法操作类,实现抽象方法; 

public class OperationAdd extends Operation {

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

}
public class OperationDiv extends Operation {
    @Override
    public double getResult() throws Exception {
        if(getNumberB() == 0) {
            throw new Exception("被除数不能为0!");
        }
        return getNumberA() / getNumberB();
    }
}

生成操作对象的工厂类:

public class OperationFactory {

    public static Operation createOperation(String operate) throws Exception {
        Operation operation = null;
        switch(operate.trim()) {
            case "+":
                operation = new OperationAdd();
                break;
            case "-" :
                operation = new OperationSub();
                break;
            case "*" :
                operation = new OperationMul();
                break;
            case "/" :
                operation = new OperationDiv();
                break;
            default:
                throw new Exception("输入的运算符号有误!");
        }
        return operation;
    }

}

客户端代码: 

public class OperationMain {

    public static void main(String[] args) throws Exception {
        Operation operation = OperationFactory.createOperation("*");
        operation.setNumberA(15);
        operation.setNumberB(18);
        System.out.println(operation.getResult());
    }

}

如果再增加其他运算方法如开方,新建开方操作类,继承操作类,并实现抽象方法,并且在工厂类的switch-case中增加分支即可!

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值