工厂方法

与简单工厂模式相比,工厂方法模式对工厂类进行了抽象,把逻辑实现放在了具体的工厂(社会分工开始,工厂开始细分,每个工厂只生产一个产品)


      1 #include <iostream>
      2 #include <string>
      3 
      4 using namespace std;
      5 
      6 class Car
      7 {
      8 public:
      9     virtual ~Car(){}
     10     virtual void run()=0;
     11 };
     12 
     13 class QQ: public Car
     14 {
     15 public:
     16     void run()
     17     {
     18         cout << "QQ run ..." << endl;
     19     }
     20 };
     21 
     22 class BMW: public Car
     23 {
     24 public:
     25     void run()
     26     {
     27         cout << "BMW run ..." << endl;
     28     }
     29 };
     30 
     31 class CarFactory
     32 {
     33 public:
     34     virtual ~CarFactory(){};
     35     virtual Car* createCar()=0;
     36 };
     37 
     38 class QQFactory: public CarFactory
     39 {
     40 public:
     41     Car* createCar()
     42     {
     43         return new QQ();
     44     }
     45 };
     46 
     47 class BMWFactory: public CarFactory
     48 {
     49 public:
     50     Car* createCar()
     51     {
     52         return new BMW();
     53     }
     54 };
     55 
     56 
     57 int main()
     58 {
     59     CarFactory* factory = new QQFactory();
     60     Car * car = factory->createCar();
     61     car->run();
     62     delete car;
     63     delete factory;
     64 
     65     factory = new BMWFactory();
     66     car = factory->createCar();
     67     car->run();
     68     delete car;
     69     delete factory;
     70 }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值