• 设计模式2---工厂模式


    为了解决简单工厂模式的缺点,我们通过接口IFactory抽象出工厂类,然后每次增加一个操作类,我就增加工厂类,

    从而达到:对扩展开放,对修改关闭。

    还是计算器的问题:

    UML如下:

    factory 基类:

    public interface IOperatorFactory {
        AbstractOperator CreateOperation();
    }

    工厂类:

    package com.jayfulmath.designpattern.factory;
    
    import com.jayfulmath.designpattern.samplefactory.operator.AbstractOperator;
    import com.jayfulmath.designpattern.samplefactory.operator.OperatorAdd;
    
    public class AddFactory implements IOperatorFactory {
    
        @Override
        public AbstractOperator CreateOperation() {
            // TODO Auto-generated method stub
            return new OperatorAdd();
        }
    
    }
    package com.jayfulmath.designpattern.factory;
    
    import com.jayfulmath.designpattern.samplefactory.operator.AbstractOperator;
    import com.jayfulmath.designpattern.samplefactory.operator.OperatorPlus;
    
    public class PlusFactory implements IOperatorFactory {
    
        @Override
        public AbstractOperator CreateOperation() {
            // TODO Auto-generated method stub
            return new OperatorPlus();
        }
    
    }

    main:

    package com.jayfulmath.designpattern.factory;
    
    import com.jayfulmath.designpattern.main.BasicExample;
    import com.jayfulmath.designpattern.samplefactory.operator.AbstractOperator;
    
    public class FactoryMain extends BasicExample {
    
        @Override
        public void startDemo() {
            // TODO Auto-generated method stub
            IOperatorFactory addFactory = new AddFactory();
            AbstractOperator addOperation = addFactory.CreateOperation();
            addOperation.NumberA = 1;
            addOperation.NumberB = 2;
            System.out.println("[FactoryMain]"+addOperation.NumberA+" add "+addOperation.NumberB+" = "+addOperation.GetResult());    
        }
    
    }

    工厂接口生成操作基类。

  • 相关阅读:
    使用jsonEditor打造一个复杂json编辑器
    【原创】一次“诡异”的容器Unix Socket通信问题分析
    【原创】Ingress-Nginx-Controller的Metrics监控源码改造简析
    IDEA+DevTools实现热部署功能
    ElementUI按需引入各种组件
    vue-cli4.0更新后怎样将eslint关闭
    Mysql修改字段名、修改字段类型
    博客搬家CSDN
    如何优雅的处理Restful
    java系列之注解
  • 原文地址:https://www.cnblogs.com/deman/p/4123250.html
Copyright © 2020-2023  润新知