zoukankan      html  css  js  c++  java
  • 工厂模式三部曲之工厂方法模式

    工厂方法模式有四要素

    • 产品接口
    • 产品实现
    • 工厂接口
    • 工厂实现

    和简单工厂模式的区别

    简单工厂模式只有三个要素,它没有工厂接口,并且得到的产品方法一般是静态的。因为没有工厂接口,所以在工厂实现的扩展性方面较弱,可以算作工厂方法模式的简化版。

    计算器的例子用工厂方法模式实现

    类图如下:

    项目如下:

    代码如下:

    IFactory:

    public interface IFactory {
        public Operation createOperation();
    }

    AddFactory:

    public class AddFactory implements IFactory {
    
        @Override
        public Operation createOperation() {
            return new AddOperation();
        }
    
    }

    SubFactory:

    public class SubFactory implements IFactory {
    
        @Override
        public Operation createOperation() {
            return new SubOperation();
        }
    
    }

    MulFactory:

    public class MulFactory implements IFactory {
    
        @Override
        public Operation createOperation() {
            return new MulOperation();
        }
    
    }

    DivFactory:

    public class DivFactory implements IFactory {
    
        @Override
        public Operation createOperation() {
            return new DivOperation();
        }
    
    }

    剩下的类和简单工厂模式的一样。

    可以参考:http://www.cnblogs.com/DarrenChan/p/5661356.html

    测试:

    IFactory fac = new DivFactory();
    Operation oper = fac.createOperation();
    oper.setNumber1(3.3);
    oper.setNumber2(5.12);
    System.out.println(oper.getResult());
  • 相关阅读:
    三元组数据结构
    线性表的顺序表示和实现 数据结构
    【欧拉计划1】Multiples of 3 and 5
    strcmp()与strcmpi()函数 C语言
    指向函数的指针 C语言
    const限定符声明 C语言
    Java环境搭建与配置
    栈的C语言实现
    【欧拉计划2】Even Fibonacci numbers
    单链表的表示和实现 数据结构
  • 原文地址:https://www.cnblogs.com/DarrenChan/p/5661426.html
Copyright © 2011-2022 走看看