简单工厂模式

实现简单的加减乘除。

1.运算类

package com.gzy.designpattern.simplefactory;

import lombok.Data;

/*
 * @program: mybatis-plus
 * @description: 运算类
 * @author: gaozhiyuan
 * @create: 2019-02-13 00:22
 */
@Data
abstract class Operation {
    private double numberA = 0;
    private double numberB = 0;
    abstract double getResult();
}

2.加法类,继承运算类

package com.gzy.designpattern.simplefactory;

/*
 * @program: mybatis-plus
 * @description: 加法类,继承运算类
 * @author: gaozhiyuan
 * @create: 2019-02-13 00:24
        */
class OperationAdd extends Operation {
    @Override
    double getResult() {
        return this.getNumberA() + this.getNumberB();
    }
}

3.除法,继承运算类

package com.gzy.designpattern.simplefactory;

import org.junit.Assert;

/*
 * @program: mybatis-plus
 * @description: 除法,继承运算类
 * @author: gaozhiyuan
 * @create: 2019-02-13 00:32
 */
 class OperationDiv extends Operation {
    @Override
    double getResult() {
        Assert.assertTrue("除数不能为 0 !", this.getNumberB() != 0);
        return this.getNumberA()/this.getNumberB();
    }



}

4.乘法,继承运算类

package com.gzy.designpattern.simplefactory;

/*
 * @program: mybatis-plus
 * @description: 乘法,继承运算类
 * @author: gaozhiyuan
 * @create: 2019-02-13 00:31
 */
 class OperationMul extends Operation {
    @Override
    double getResult() {
        return this.getNumberA() * this.getNumberB();
    }
}

5.减法类,继承运算类

package com.gzy.designpattern.simplefactory;

/*
 * @program: mybatis-plus
 * @description: 减法类,继承运算类
 * @author: gaozhiyuan
 * @create: 2019-02-13 00:26
 */
class OperationSub extends Operation{

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

6.简单运算工厂

package com.gzy.designpattern.simplefactory;

/*
 * @program: mybatis-plus
 * @description: 简单运算工厂
 * @author: gaozhiyuan
 * @create: 2019-02-13 00:54
 */
 class OperationFactory {
    public static Operation createOperation(String operate){
        Operation operation = null;
        switch (operate) {
            case "+":
                operation = new OperationAdd();
                break;
            case "-":
                operation = new OperationSub();
                break;
            case "*":
                operation = new OperationMul();
                break;
            case "/":
                operation = new OperationDiv();
                break;
        }
        return operation;
    }
}

7.测试类

package com.gzy.designpattern.simplefactory;

/*
 * @program: mybatis-plus
 * @description: test
 * @author: gaozhiyuan
 * @create: 2019-02-13 01:06
 */
public class Test {
    public static void main(String[] args) {
        Operation operation = OperationFactory.createOperation("+");
        operation.setNumberA(1);
        operation.setNumberB(0);
        System.out.println(operation.getResult());
    }
}

测试结果:

 

1.0

Process finished with exit code 0

 

posted @ 2019-02-14 00:29  sheni  阅读(174)  评论(0编辑  收藏  举报