设计模式之 Factory(简单工厂模式)通俗理解

1 工厂模式定义

 提供创建对象的接口。

2 为什么此模式是如此常用?

因为工厂模式就相当于创建实例对象的 new,我们经常要根据类 Class 生成实例对象,如 A a=new A() 工厂模式也是用来创建实例对象的,所以以后new 时就要多个心眼,是否可以考虑实用工厂模式,虽然这样做,可能多做一些工作,但会给你系统带来更大的可扩展性和尽量少的修改量。

3 如何使用?

举例:加减乘除运算。

package xx.study.design.simpleFactory;
/**
 * 客户端使用
 */
public class SimpleFactoryDemo {
    public static void main(String[] args) {
        char oprate ='*';
        Operation oper = SimpleFactory.operation(oprate);
        oper.setNumberA(20);
        oper.setNumberB(2);
        double result = oper.getResult();
        System.out.println(oper.getNumberA()+""+oprate+""+oper.getNumberB()+"="+result);
    }
}
package xx.study.design.simpleFactory;

/**
 * 简单工厂类
 */
public class SimpleFactory {
    public static Operation operation(char operate) {
        Operation oper = null;
        switch (operate) {
            case '+':
                oper = new Add();
                break;
            case '-':
                oper = new Sub();
                break;
            case '*':
                oper = new Mul();
                break;
            case '/':
                oper = new Div();
                break;
            default:
                break;
        }
        return oper;
    }
}
package xx.study.design.simpleFactory;

/**
 * Operatio运算类
 *
 */
public class Operation {
    private double numberA = 0;
    private double numberB = 0;
    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 double getResult() {
        double result =0;
        return result;
    }
}
package xx.study.design.simpleFactory;

/**
 * 加法运算
 * @author 15680
 *
 */
public class Add extends Operation {
    @Override
    public double getResult() {
        double result =0;
        result = getNumberA()+getNumberB();
        return result;
    }
}
/**
 * 减法运算类
 * @author 15680
 *
 */
 class Sub extends Operation {
    @Override
    public double getResult() {
        double result =0;
        result = getNumberA()-getNumberB();
        return result;
    }
}
/**
 * 乘法运算类
 * @author 15680
 *
 */
class Mul extends Operation {
    @Override
    public double getResult() {
        double result =0.0;
        result = getNumberA()*getNumberB();
        return result;
    }
}
/**
 * 除法运算类
 * @author 15680
 *
 */
class Div extends Operation {
    @Override
    public double getResult() {
        double result =0.0;
        if(getNumberB()==0) {
            System.out.println("除数不能为0");
            return -1;
        }
        result= getNumberA()/getNumberB();
        return result;
    }
}

 

你可能感兴趣的:(23种设计模式,Simple,Factory,简单工厂模式,java,factory)