zoukankan      html  css  js  c++  java
  • 大话设计模式笔记(六)の工厂方法模式

    栗子回顾

    简单工厂模式:
    https://www.cnblogs.com/call-me-devil/p/10926633.html

    运算类使用工厂方法模式实现

    UML图

    代码实现

    工厂接口

    /**
     * 工厂接口
     * Created by callmeDevil on 2019/7/7.
     */
    public interface IFactory {
        /**
         * 创建运算类
         *
         * @return
         */
        BaseOperation createOpertaion();
    }
    

    运算基础类

    为节省篇章,详见简单工厂模式,此处省略。
    以下加减乘除运算类(OperationAdd、OperationSub、OperationMul、OperationDiv)同。

    加法工厂

    /**
     * 加法工厂
     * Created by callmeDevil on 2019/7/7.
     */
    public class AddFactory implements IFactory{
    
        @Override
        public BaseOperation createOpertaion() {
            return new OperationAdd();
        }
    
    }
    

    减法工厂

    /**
     * 减法工厂
     * Created by callmeDevil on 2019/7/7.
     */
    public class SubFactory implements IFactory {
    
        @Override
        public BaseOperation createOpertaion() {
            return new OperationSub();
        }
    
    }
    

    乘法工厂

    /**
     * 乘法工厂
     * Created by callmeDevil on 2019/7/7.
     */
    public class MulFactory implements IFactory{
    
        @Override
        public BaseOperation createOpertaion() {
            return new OperationMul();
        }
    
    }
    

    除法工厂

    /**
     * 除法工厂
     * Created by callmeDevil on 2019/7/7.
     */
    public class DivFactory implements IFactory{
    
        @Override
        public BaseOperation createOpertaion() {
            return new OperationDiv();
        }
    
    }
    

    测试

    /**
     * 工厂方法模式测试
     * Created by callmeDevil on 2019/7/7.
     */
    public class Test {
    
        public static void main(String[] args) {
            IFactory operFactory = new AddFactory();
            BaseOperation oper = operFactory.createOpertaion();
            oper.setNumA(1);
            oper.setNumB(2);
            double result = oper.getResult();
            System.out.println("加法测试结果:" + result);
        }
    
    }
    

    测试结果

    加法测试结果:3.0
    

    工厂方法模式

    与简单工厂比较

    简单工厂模式的最大优点在于工厂类中,包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。

    定义

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

    结构图

    总结

    工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的,也就是说,工厂方法把简单工厂的内部逻辑判断移到了客户端代码进行。你想要加功能,本来是改工厂类的,而现在是修改客户端。

  • 相关阅读:
    JAVASCRIPT函数定义表达式和函数声明的区别
    单链表
    Asp.net+jquery+ajaxpro异步仿Facebook纵向时间轴效果
    基于Hadoop开发网络云盘系统客户端界面设计初稿
    U盘安装CentOS 6.4 + Windows 7双系统 (Windows 7下安装 CentOS 6.4)
    Last_SQL_Errno: 1050
    delphi 7中使用idhttp抓取网页 解决假死现象(使用TIdAntiFreezeControl控件)
    继承CWnd自绘按钮
    gcc编译器对宽字符的识别
    解决Qt程序发布时中文乱码问题(通过QApplication.addLibraryPath加载QTextCodec插件)
  • 原文地址:https://www.cnblogs.com/call-me-devil/p/11146442.html
Copyright © 2011-2022 走看看