(五)工厂模式

这个跟之前的简单工厂模式的不同之处在于工厂类factory作为基类存在,算法类operation作为子类存在,不同的工厂子类生成对应大算法子类,不难理解,就直接贴代码了
#include <iostream>
#include <string>

using namespace std;

//算法类 
class operation
{
      public:
             operation() {}
             void set_data( double a, double b )
             {    A=a;      B=b;   }
             virtual double get_result() {}
      protected:
                double A,B;
};

class add : public operation
{
      double get_result()
      {
             return A+B;
      }
};

class sub : public operation
{
      double get_result()
      {
             return A-B;
      }
};



//工厂类
class operation_factory
{
      public:
             virtual operation *create_operation() {}
}; 

class add_factory : public operation_factory
{
      public:
             operation *create_operation()
             {
                       return new add;
             }
};

class sub_factory : public operation_factory
{
      public:
             operation *create_operation()
             {
                       return new sub;
             }
};

int main()
{
    cout << "输入你的数据" << endl;
    double a,b;
    cin >> a >> b;
    operation_factory *f = new add_factory;
    operation *op1 = f->create_operation();
    op1->set_data( a, b );
    cout << op1->get_result() << endl;
    getchar();
    getchar();
}


修正了简单工厂模式中不遵守开放-封闭原则。工厂方法模式把选择判断移到了客户端去实现,如果想添加新功能就不用修改原来的类,直接修改客户端即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值