美文网首页
工厂方法模式(Factory Method)

工厂方法模式(Factory Method)

作者: bobcorbett | 来源:发表于2017-08-16 09:45 被阅读0次

    工厂方法模式(Factory Method),定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

    主方法

    /**
     * Created by king on 2017/7/8.
     */
    public class main {
        public static void main(String[] args) {
            IFactory operFactory = new AddFactory();
            Operation oper = operFactory.CreateOperation();
            oper.setNumberA(4);
            oper.setNumberB(6);
            double result = oper.getResult();
            System.out.println(result);
        }
    }
    

    工厂接口类

    public interface IFactory {
        Operation CreateOperation();
    }
    

    接口实现类

    public class AddFactory implements IFactory {
    
        public Operation CreateOperation() {
            return new OperationAdd();
        }
    }
    
    public class DivFactory implements IFactory {
        public Operation CreateOperation() {
            return new OperationDiv();
        }
    }
    
    public class MulFactory implements IFactory {
        public Operation CreateOperation() {
            return new OperationMul();
        }
    }
    
    public class SubFactory implements IFactory {
        public Operation CreateOperation() {
            return new OperationSub();
        }
    }
    

    Operation相关见《简单工厂模式》

    相关文章

      网友评论

          本文标题:工厂方法模式(Factory Method)

          本文链接:https://www.haomeiwen.com/subject/egnbrxtx.html