zoukankan      html  css  js  c++  java
  • 设计模式 之 《简单工厂模式》

    主要用于创建对象。新添加类时,不会影响以前的系统代码。

     

    核心思想是用一个工厂来根据输入的条件产生不同的类,然后根据不同类的virtual函数得到不同的结果。

     

    advantage:适用于不同情况创建不同的类时

    disadvantage:客户端必须要知道基类和工厂类,耦合性差

     

    #ifndef __SIMPLE_FACTORY_MODEL__
    #define __SIMPLE_FACTORY_MODEL__
    
    //运算类
    class Operation
    {
    public:
        virtual double getResult() = 0;
    
    public:
        double numberA;
        double numberB;
    
    };
    
    //实际 加 减 乘 除 算法类
    class OperationAdd : public Operation
    {
    public:
        double getResult() {return numberA+numberB;}
    };
    
    //简单工厂类
    class SimpleFactory
    {
    public:
        static Operation* calculation(char c);
        
    };
    
    Operation* SimpleFactory::calculation(char c)
    {
        Operation* oper = NULL;
        switch (c)
        {
        case '+':
            oper = new OperationAdd();
            break;
        default:
            break;
        }
        return oper;
    }
    
    #endif //__SIMPLE_FACTORY_MODEL__
    
    
    //客户端
    #include "SimpleFactoryModel.h"
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        double a, b;
        char c;
        cin>>a>>c>>b;
    
        Operation* oper = SimpleFactory::calculation(c);
        oper->numberA = a;
        oper->numberB = b;
        cout<<a<<" + "<<b<<" = "<<oper->getResult()<<endl;
    
        return 0;
    }
  • 相关阅读:
    ‎CocosBuilder 学习笔记(2) ccbi 文件结构分析
    ‎Cocos2d-x 学习笔记(22) TableView
    ‎Cocos2d-x 学习笔记(21.1) ScrollView “甩出”效果与 deaccelerateScrolling 方法
    ‎Cocos2d-x 学习笔记(21) ScrollView (CCScrollView)
    pkg-config
    变量定义
    perror 与 strerror
    popen and system
    exit
    uint8_t
  • 原文地址:https://www.cnblogs.com/MrGreen/p/3281635.html
Copyright © 2011-2022 走看看