• 工厂模式


    //
    //  main.cpp
    //  test
    //
    //  Created by sun on 15/11/14.
    //  Copyright (c) 2015年 sun. All rights reserved.
    //
    
    #include <iostream>
    using namespace std;
    
    
    int main(int argc, const char * argv[])
    {
    
        int a;
        printf("请输入数字a:
    ");
        scanf("%d",&a);
        
        int symbol;
        printf("请输入运算符(+-*/):
    ");
    
        scanf("%d",&symbol);
        
        printf("请输入数字b:
    ");
        int b;
        scanf("%d",&b);
        cout<<"result:";
        switch (symbol) {
            case 1:
                cout<<a+b<<endl;
                break;
            case 2:
                cout<<a-b<<endl;
                break;
            case 3:
                cout<<a*b<<endl;
                break;
            case 4:
                cout<<a/b<<endl;
                break;
            default:
                break;
        }
        
        return 0;
    }
    
    

    工厂模式

    //
    //  main.cpp
    //  test
    //
    //  Created by sun on 15/11/14.
    //  Copyright (c) 2015年 sun. All rights reserved.
    //
    
    #include <iostream>
    using namespace std;
    class Operation
    {
    
    public:
        double _a;
        double _b;
        Operation()
        {
    
        }
    
        virtual double GetResult()
        {
            double result=0;
            return result;
        }
    
        
    };
    
    class OperationAdd:public Operation
    {
      
    public:
    
        OperationAdd()
        {
            Operation();
        }
       double GetResult ()
        {
            return _a+_b;
        }
    };
    
    class OperationSub:public Operation
    {
    public:
        OperationSub()
        {
            Operation();
        }
        double GetResult ()
        {
            return _a-_b;
        }
    };
    
    class OperationFactory
    {
    public:
        static Operation* create(int operate)
        {
            Operation* oper;
            switch (operate) {
                case 1:
                    oper=new OperationAdd();
                    break;
                case 2:
                    oper=new OperationSub();
                    break;
                default:
                    break;
            }
            return oper;
        }
    };
    
    int main(int argc, const char * argv[])
    {
        Operation* oper;
        oper=OperationFactory::create(2);
        oper->_a=1;
        oper->_b=3;
        cout<<oper->GetResult()<<endl;
        return 0;
    }
    
    
    
  • 相关阅读:
    [ARC117F]Gateau
    [ARC117D]Miracle Tree
    [loj3504]支配
    [gym102511K]Traffic Blights
    [loj3501]图函数
    [loj3503]滚榜
    [loj3500]矩阵游戏
    [loj2135]幻想乡战略游戏
    [cf720D]Slalom
    [cf1349E]Slime and Hats
  • 原文地址:https://www.cnblogs.com/yufenghou/p/4963924.html
Copyright © 2020-2023  润新知