首页 » Java » Java设计模式之简单工厂模式

Java设计模式之简单工厂模式

原文 http://blog.csdn.net/qq_35508033/article/details/78820157

2017-12-17 02:00:19阅读(562)

大话设计模式豆瓣地址:https://read.douban.com/reader/ebook/32943798/

考虑用一个单独的类来做这个创造实例的过程,这就是工厂

前提准备:

public abstract class Operation {//操作类抽象类
    public double numberA;
    public double numberB;
    public abstract double result();
}

public class OperationAdd extends Operation {//加法类
    @Override
    public double result() {
        return numberA + numberB;
    }
}

public class OperationDiv extends Operation {//除法类
    @Override
    public double result() {
        if (numberB == 0) {
            throw new RuntimeException("divided by 0");
        }
        return numberA / numberB;
    }
}

public class OperationMul extends Operation {//乘法类
    @Override
    public double result() {
        return numberA * numberB;
    }
}

public class OperationSub extends Operation {//减法类
    @Override
    public double result() {
        return numberA - numberB;
    }
}

简单运算工厂类:

public class OperationFactory {//操作类工厂类
    public static Operation createOperation(char operator) {
        Operation operation = null;
        switch (operator) {
            case '+':
                operation = new OperationAdd();
                break;
            case '-':
                operation = new OperationSub();
                break;
            case '*':
                operation = new OperationMul();
                break;
            case '/':
                operation = new OperationDiv();
                break;
            default:
                throw new RuntimeException("unsupported operation");
        }
        return operation;
    }
}

客户端代码:

public class Calculator {//使用工厂方法生成实例完成运算操作
    public static void main(String[] args) {
        Operation operation;
        char operator;
        operator = '+';
        operation = OperationFactory.createOperation(operator);
        operation.numberA = 1.2;
        operation.numberB = 2.3;
        System.out.println(operation.result());
    }
}
最后,我们来看看这几个类的结构图:

<a href=Java设计模式之简单工厂模式" src="http://img.blog.csdn.net/20171216155516073?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzU1MDgwMzM=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹