zoukankan      html  css  js  c++  java
  • 工厂模式

    意图:定义一个用于创建对象的接口,让子类决定实例化哪一个类。使一个类的实例化延迟到其子类。


    ### 实现(简单工厂):
    public class OperationFactory {
        public static Operation createOperate(String operate) {
            Operation oper = null;
    
            switch (operate) {
                case "+": oper = new OperationAdd(); break;
                case "-": oper = new OperationSub(); break;
                case "*": oper = new OperationMul(); break;
                case "/": oper = new OperationDiv(); break;
            }
    
            return oper;
        }
    
        // 客户端
        public static void main(String[] args) {
            Operation oper = OperationFactory.createOperate("+");
            oper.numberA = 1;
            oper.numberB = 2;
            double result = oper.getResult();
        }
    
    }
    

    ### 实现(工厂方法):
    // 工厂接口
    public interface IFactory {
        Operation createOperation();
    }
    
    // 加法工厂
    public class AddFactory implements IFactory {
        public Operation createOperation() {
            return new OperationAdd();
        }
    }
    
    // 减法工厂、乘法工厂、除法工厂
    ...
    
    // 客户端
    IFactory operFactory = new AddFactory();
    Operation oper = operFactory.CreateOperation();
    oper.numberA = 1;
    oper.numberB = 2;
    double result = oper.getResult();
  • 相关阅读:
    Runtime类
    递归(99乘法表)
    计算某天是在一年中的第几天
    数组逆序输出
    打印数组格式
    选择排序(直接把最小或最大的数选出来排列)
    冒泡排序
    比较两个字符数组是否相等
    汉字转阿斯克马值
    R语言调用C函数
  • 原文地址:https://www.cnblogs.com/hippiebaby/p/5468864.html
Copyright © 2011-2022 走看看