工厂模式(Factory)
简单工厂
只有一个工厂,即一个类负责创建不同类的实例。通常使用static静态方法来创建对象,不需要传递工厂类来创建实例。
优点:
缺点:
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| #include <iostream>
using namespace std;
class Car { public: virtual void drive() = 0; virtual ~Car() {} };
class BydCar : public Car { public: void drive() override { cout << "Driving BydCar" << endl; } };
class TeslaCar : public Car { public: void drive() override { cout << "Driving TeslaCar" << endl; } };
class CarFactory { public: static Car* createCar(const string& brand) { if (brand == "Byd") return new BydCar(); else if (brand == "Tesla") return new TeslaCar(); else return nullptr; } };
int main() { Car *bydCar = CarFactory::createCar("Byd"); bydCar->drive();
delete bydCar; return 0; }
|
工厂方法