工厂方法(factory-method)模式

1.意图

定义用于创建对象的接口,但是让子类决定要实例化哪个类。 工厂方法允许类将实例化推迟到子类。

2.解释

  • 它提供了一种将实例化逻辑委托给子类的方法。
  • 在基于类的编程中,工厂方法模式是使用工厂方法来处理创建对象的问题的创建模式,而不必指定将要创建的对象的确切类。 这可以通过调用工厂方法(在接口中指定并由子类实现)来实现,或者在基类中实现,并且可选地被派生类覆盖,而不是调用构造函数。

3.代码实例

public enum OperatorType {

    ADD("+"), SUB("-"), DIV("/"), MUL("*");

    private String operator;

    OperatorType(String operator) {
        this.operator = operator;
    }

    @Override
    public String toString() {
        return "OperatorType{" +
                "operator='" + operator + '\'' +
                '}';
    }
}
public interface Operator {

    OperatorType getOperatorType();

}
public interface OperatorFactory {

    Operator manufactureOperator(OperatorType operatorType);

}
public class AddOperator implements Operator{

    private OperatorType operatorType;

    public AddOperator(OperatorType operatorType){
        this.operatorType = operatorType;
    }


    public OperatorType getOperatorType() {
        return operatorType;
    }

    @Override
    public String toString() {
        return "AddOperator{" +
                "operatorType=" + operatorType +
                '}';
    }
}
public class AddOperatorFactory implements OperatorFactory {

    public Operator manufactureOperator(OperatorType operatorType) {
        return new AddOperator(operatorType);
    }
}
public class App {

    private static final Logger logger = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        OperatorFactory factory = new AddOperatorFactory();
        Operator operator = factory.manufactureOperator(OperatorType.DIV);
        logger.info(operator.toString());
    }

}

你可能感兴趣的:(设计模式)