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

    1】什么是工厂方法模式?
    
    定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类当中。核心工厂类不再负责产品的创建,这样核心类成为一个抽象工厂角色,仅负责具体工厂子类必须实现的接口,这样进一步抽象化的好处是使得工厂方法模式可以使系统在不修改具体工厂角色的情况下引进新的产品。
    
    【2】工厂方法模式代码示例
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Operation
    {
    public:
        double numberA;
        double numberB;
    
        virtual double getResult()
        {
            return 0;
        }
    };
    
    class addOperation : public Operation
    {
        double getResult()
        {
            return numberA + numberB;
        }
    };
    
     
    class subOperation : public Operation
    {
        double getResult()
        {
            return numberA - numberB;
        }
    };
    
    class mulOperation : public Operation
    {
        double getResult()
        {
            return numberA * numberB;
        }
    };
    
    class divOperation : public Operation
    {
        double getResult()
        {
            return numberA / numberB;
        }
    };
    
    class IFactory
    {
    public:
        virtual Operation *createOperation() = 0;
    };
    
    class AddFactory : public IFactory
    {
    public:
        static Operation *createOperation()
        {
            return new addOperation();
        }
    };
    
    
    class SubFactory : public IFactory
    {
    public:
        static Operation *createOperation()
        {
            return new subOperation();
        }
    };
    
    class MulFactory : public IFactory
    {
    public:
        static Operation *createOperation()
        {
            return new mulOperation();
        }
    };
    
    class DivFactory : public IFactory
    {
    public:
        static Operation *createOperation()
        {
            return new divOperation();
        }
    };
    
    int main()
    {
        Operation *oper = MulFactory::createOperation();
        oper->numberA = 9;
        oper->numberB = 99;
        cout << oper->getResult() << endl;
        return 0;
    }
  • 相关阅读:
    BZOJ 1609: [Usaco2008 Feb]Eating Together麻烦的聚餐( LIS )
    BZOJ 1660: [Usaco2006 Nov]Bad Hair Day 乱发节( 单调栈 )
    BZOJ 1620: [Usaco2008 Nov]Time Management 时间管理( 二分答案 )
    BZOJ 1639: [Usaco2007 Mar]Monthly Expense 月度开支( 二分答案 )
    JAVA
    CodeForces-327A-Flipping Game
    Python学习笔记(九)- 变量进阶、函数进阶
    HDU6480-A Count Task-字符串+公式
    JQuery学习笔记(一)
    JAVA
  • 原文地址:https://www.cnblogs.com/leijiangtao/p/4534644.html
Copyright © 2011-2022 走看看