02. 工厂方法模式

工厂方法模式:在简单工厂方法模式的基础上,把创建对象的方法virtual化,然后创造多个工厂,每个工厂产生一个类型的产品。特点:每增加一个产品,需要增加一个相应生产的工厂。

/**
 * @file car_factory.h
 * @brief car factory
 * @author timeshark
 * @version 1.0
 * @date 2018-08-06
 */

#ifndef CAR_FACTORY
#define CAR_FACTORY

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

class Car {
public:
    virtual void print() = 0;
};

class Benz : public Car {
public:
    void print() {
        cout << "this is benz" << endl;
    }
};

class Bmw : public Car {
public:
    void print() {
        cout << "this is bmw" << endl;
    }
};

class Factory {
public:
    virtual Car* create_car() = 0;
};

class FactoryA : public Factory {
public:
    Car* create_car() {
        cout << "*** A factory only create benz ***" << endl;
        return new Benz();
    }
};

class FactoryB : public Factory {
public:
    Car* create_car() {
        cout << "*** B factory only create bmw ***" << endl;
        return new Bmw();
    }
};

#endif
/**
 * @file main.cpp
 * @brief factory method
 * @author timeshark
 * @version 1.0
 * @date 2018-08-06
 */

#include "car_factory.h"

int main() {
    FactoryA a_factory;
    Car* b = a_factory.create_car();
    if (b) {
        b->print();
    }

    FactoryB b_factory;
    Car* c = b_factory.create_car();
    if (c) {
        c->print();
    }

    return 0;
}

输出:

猜你喜欢

转载自blog.csdn.net/x_shuck/article/details/81456904
今日推荐