设计模式之简单工厂模式

最近在学习大话设计模式,写一下自己的学习体会和实现小例子。

理解:自定义一个接口,根据不同的需求创建实现类,而工厂模式主要解决接口选择的问题,根据条件的不同动态的创建实例

简单实例(计算器):

接口:

public interface Calculation {
    double getResult(double a, double b) throws Exception;
}

 实现类:加:

public class Add implements Calculation {
    @Override
    public double getResult(double a, double b) {
        return a + b;
    }
}

 

减:

public class Reduce implements Calculation {
    @Override
    public double getResult(double a, double b) {
        return  a - b;
    }
}

乘:

public class Ride implements Calculation {


    @Override
    public double getResult(double a, double b) {
        return a * b;
    }
}

除:

public class Divide implements Calculation {
    @Override
    public double getResult(double a, double b) throws Exception {
        if (b != 0) {
            return a / b;
        } else {
            throw new Exception("两数相除,除数不能为 0");
        }
    }
}

id 配置:

(接口变量默认public static final,简单配置)

public interface Constant {
    int add = 1;
    int reduce = 2;
    int ride = 3;
    int divide = 4;
}

工厂类:

public class CalculationFactory {

    public static Calculation createCalution(int id) {
        Calculation calculation = null;
        switch (id) {
            case Constant.add:
                calculation = new Add();
                break;
            case Constant.reduce:
                calculation = new Reduce();
                break;
            case Constant.ride:
                calculation = new Ride();
                break;
            case Constant.divide:
                calculation = new Divide();
                break;
            default:
        }
        return calculation;
    }
}

 调用类:

public class Main {

    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            double a;
            double b;
            int c;
            try {
                System.out.println("请输入第一个数字");
                a = scanner.nextDouble();
                System.out.println("请输入第二个数字");
                b = scanner.nextDouble();
                System.out.println("1:加 2:减 3:乘 4:除");
                c = scanner.nextInt();
                System.out.println("运算结果为:");
            } catch (Exception e) {
                break;
            }
            Calculation calculation = CalculationFactory.createCalution(c);
            if (calculation != null) {
                try {
                    System.out.println(calculation.getResult(a, b) + "");
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值