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());
  • 相关阅读:
    Java学习之路----计算圆形的面积和周长
    数据库系统的基本组成内容
    软件测试的含义以及测试的对象
    wg sync.WaitGroup执行顺序
    go channel
    字符串操作
    scanf
    py停止工作
    jira索引失败
    py kafka
  • 原文地址:https://www.cnblogs.com/DarrenChan/p/5661426.html
Copyright © 2011-2022 走看看