工厂模式

72 阅读1分钟

简单工厂模式实现方式

// 计算类的基类
@Setter
@Getter
public abstract class Operation {
    private double value1 = 0;
    private double value2 = 0;
    protected abstract double getResule();
}

//加法
public class OperationAdd extends Operation {
    @Override
    protected double getResule() {
        return getValue1() + getValue2();
    }
}
//减法
public class OperationSub extends Operation {
    @Override
    protected double getResule() {
        return getValue1() - getValue2();
    }
}
//乘法
public class OperationMul extends Operation {
    @Override
    protected double getResule() {
        return getValue1() * getValue2();
    }
}
//除法
public class OperationDiv extends Operation {
    @Override
    protected double getResule() {
        if (getValue2() != 0) {
            return getValue1() / getValue2();
        }
        throw new IllegalArgumentException("除数不能为零");
    }
}
复制代码
//工厂类
public class OperationFactory {

    public static Operation createOperation(String operation) {
        Operation oper = null;
        switch (operation) {
            case "add":
                oper = new OperationAdd();
                break;
            case "sub":
                oper = new OperationSub();
                break;
            case "mul":
                oper = new OperationMul();
                break;

            case "div":
                oper = new OperationDiv();
                break;
            default:
                throw new UnsupportedOperationException("不支持该操作");
        }
        return oper;
    }
}
复制代码
public static void main(String[] args) {
  Operation operationAdd = OperationFactory.createOperation("add");
  operationAdd.setValue1(1);
  operationAdd.setValue2(2)
  System.out.println(operationAdd.getResule());
}
复制代码

工厂方法

//工厂接口
public interface IFactory {
    Operation CreateOption();
}

//加法类工厂
public class AddFactory implements IFactory {
    public Operation CreateOption() {
        return new OperationAdd();
    }
}

//减法类工厂
public class SubFactory implements IFactory {
    public Operation CreateOption() {
        return new OperationSub();
    }
}

//乘法类工厂
public class MulFactory implements IFactory {
    public Operation CreateOption() {
        return new OperationMul();
    }
}

//除法类工厂
public class DivFactory implements IFactory {
    public Operation CreateOption() {
        return new OperationDiv();
    }
}
复制代码
public class Client {
    public static void main(String[] args) {
      //减法
      IFactory subFactory = new SubFactory();
      Operation operationSub =  subFactory.CreateOption();
      operationSub.setValue1(22);
      operationSub.setValue2(20);
      System.out.println("sub:"+operationSub.getResult());
      //除法
      IFactory Divfactory = new DivFactory();
      Operation operationDiv =  Divfactory.CreateOption();
      operationDiv.setValue1(99);
      operationDiv.setValue2(33);
      System.out.println("div:"+operationSub.getResult());
    }
}
复制代码