zoukankan      html  css  js  c++  java
  • 设计模式2:策略模式工厂

    减少算法类与使用算法类之间的耦合;简化了单元测试,因为每个算法都有自己的类,可以单独测试

    Operation.h:

    #pragma once
    
    #include<iostream>
    #include<string>
    
    using namespace std;
    
    class Operation
    {
     public:
        virtual double GetResult(){return 0};
    public:
        double numA_;
        double numB_;
    };
    
    class OperationAdd :public Operation
    {
    public:
        virtual double GetResult()
        {
            return numA_+numB_;
        }
    }
    
    class OperationSub: public Operation
    {
    public:
        virtual double GetResult()
        {
            return numA_ - numB_;
        }
    };
    
    class OperationFactory    //简单模式工厂
    {
    public:
        Operation* CreateOperation(tstring oper)
        {
            Operation*op = NULL;
            if(wcscmp(oper.c_str(),L"+") == 0)
                op = new OperationAdd();
            else
                op = new OperationSub();
            return op;
        }
    };
    
    class OperationFactoryS //策略模式工厂
    {
    public:
        OperationFactionS(wstring oper)
        {
            if(wcscmp(oper.c_str(),L"+") == 0)
                op = new OperationAdd();
            else
                op = new OperationSub();
        }
        
        void SetNumA(double num){ op->numA_ = num; }    
        void SetNumB(double num){ op->numB_ = num; }  
        double GetResult() { return op->GetResult(); } 
    
    private:
        Operation *op;
    }

    main.cpp

    #define _CRTDBG_MAP_ALLOC
    #include<stdlib.h>
    #include<crtdbg.h>
    #include"Operation.h"
    
    int main()
    {
        //需要知道所有方法类
        OperationAdd opAdd;
        opAdd.numA_ = 20;
        opAdd.NumB_ = 30;
         cout << op->GetResult() << "
    ";
    
        //需要知道工厂类和所有方法类的基类,不需要知道具体的方法类
        OperationFactory fac;
        Operation* op = fac.CreateOperation(L"+");
        op->numA_ = 20;
        op->numB_ = 30;
        cout << "简单工厂:" << op->GetResult() << "
    ";
    
        //只需要知道工厂类
        OperationFactoryS *opFacs = new OperationFactoryS(L"+");
        opFacs->SetNumA(20);
        opFacs->SetNumB(30);
        cout << "策略模式工厂:" << opFacs->GetResult() << "
    ";
        delete op;
        
        _CrtDumpMemoryLeaks();
        system("pause");
        return 0;
    }
  • 相关阅读:
    python学习之ajax和可视化管理工具
    操作系统-保护模式中的特权级下
    redis 分布式锁的 5个坑,真是又大又深
    数据库之数据表控制语句
    【NoSQL】Consul中服务注册的两种方式
    netstat命令使用方法以及详解
    Dockerfile与Dockerfile实战
    Spring boot+redis实现消息发布与订阅
    怎么寻回位置不可用移动硬盘的数据
    python字符前面u,r,f等含义
  • 原文地址:https://www.cnblogs.com/Toya/p/14046622.html
Copyright © 2011-2022 走看看