设计模式之工厂方法模式---Factory-Method

1.uml

设计模式之工厂方法模式---Factory-Method_第1张图片

2. 代码

## 抽象工厂接口

interface IFactory {
    Operation CreateOperation();
}

## 抽象运算类

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;
    }
}

## 真实工厂类

 class AddFactory implements IFactory {
    @Override
    public Operation CreateOperation() {
        return new OperationAdd();
    }
}


class MulFactory implements IFactory {
    @Override
    public Operation CreateOperation() {
        return new OperationMul();
    }
}

class DivFactory implements IFactory {
    @Override
    public Operation CreateOperation() {
        return new OperationDiv();
    }
}

class SubFactory implements IFactory {
    @Override
    public Operation CreateOperation() {
        return new OperationSub();
    }
}

## 具体操作类

public class OperationAdd extends Operation {

    @Override
    public double GetResult() {
        double result = 0;
        result = getNumberA()+getNumberB();
        return result;
    }
}


public class OperationDiv extends Operation {
    @Override
    public double GetResult()  {
        try {
            double result = 0;
            if(getNumberB()==0){
                throw new Exception("除数不能为0");
            }
            result = getNumberA()/getNumberB();
            return result;
        }catch (Exception e){

        }
        return 0;
    }
}

public class OperationMul extends Operation {

    @Override
    public double GetResult() {
        double result = 0;
        result = getNumberA()*getNumberB();
        return result;
    }
}

public class OperationSub extends Operation {
    @Override
    public double GetResult() {
        double result = 0;
        result = getNumberA()-getNumberB();
        return result;
    }
}

## 测试

public static void main(String[] args){
    IFactory operFactory = new AddFactory();
    Operation oper = operFactory.CreateOperation();
    oper.setNumberA(1);
    oper.setNumberB(2);
    double result = oper.GetResult();
}

3. 总结

        工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断问题还是存在,就是说,工厂方法把简单工厂的内部逻辑判断移动了客户端代码进行。想要加功能,本来是改工厂类的,而现在是修改客户端。

        优点:克服了简单工厂违背开放-封闭原则的缺点,又保留了封装对象创建过程的优点,降低客户端和工厂的耦合性.

        缺点:每增加一个产品,相应的也要增加一个子工厂,加大了额外的开发量。

       

你可能感兴趣的:(23种设计模式,工厂模式,设计模式)