前言:设计模式方面,很多是多态模式的实现。多态涉及继承和指针。
简单工程模式:有一个工程类,可以根据输入进行生产不同的对象指针。其代码和运行结果如下:
/**
* @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:
Car* create_car(string name) {
if (0 == name.compare("benz")) {
cout << "create benz" << endl;
return new Benz();
} else if (0 == name.compare("bmw")) {
cout << "create bmw" << endl;
return new Bmw();
} else {
cout << "no this car" << endl;
return NULL;
}
}
};
#endif
/**
* @file main.cpp
* @brief simple factory
* @author timeshark
* @version 1.0
* @date 2018-08-06
*/
#include "car_factory.h"
int main() {
Factory myfactory;
Car* b = myfactory.create_car("benz");
if (b) {
b->print();
}
Car* c = myfactory.create_car("bmw");
if (c) {
c->print();
}
Car* d = myfactory.create_car("empty");
if (d) {
d->print();
}
return 0;
}
输出: