工厂模式是将对象的创建过程以及使用过承诺分离,这样可以在不改变客户端代码的前提下增加新的产品类型。主要介绍抽象工厂的设计模式,我的理解主要是把创建对象的过程再抽象为一个抽象类,然后不同的工厂就对这个总的抽象类进行重写。其实就是多态再多态。
cpp
#include <iostream>
// 抽象产品 Car
class Car {
public:
virtual void show() = 0;
};
// 抽象产品 Tire
class Tire {
public:
virtual void show() = 0;
};
// 具体产品 BMWCar
class BMWCar : public Car {
public:
void show() override {
std::cout << "This is a BMW car." << std::endl;
}
};
// 具体产品 BMWTire
class BMWTire : public Tire {
public:
void show() override {
std::cout << "This is a BMW tire." << std::endl;
}
};
// 具体产品 AudiCar
class AudiCar : public Car {
public:
void show() override {
std::cout << "This is an Audi car." << std::endl;
}
};
// 具体产品 AudiTire
class AudiTire : public Tire {
public:
void show() override {
std::cout << "This is an Audi tire." << std::endl;
}
};
// 抽象工厂类
class AbstractFactory {
public:
virtual Car* createCar() = 0;
virtual Tire* createTire() = 0;
};
// 具体工厂 BMWFactory
class BMWFactory : public AbstractFactory {
public:
Car* createCar() override {
return new BMWCar();
}
Tire* createTire() override {
return new BMWTire();
}
};
// 具体工厂 AudiFactory
class AudiFactory : public AbstractFactory {
public:
Car* createCar() override {
return new AudiCar();
}
Tire* createTire() override {
return new AudiTire();
}
};
// 测试代码
int main() {
// 创建 BMW 工厂
AbstractFactory* bmwFactory = new BMWFactory();
Car* bmwCar = bmwFactory->createCar();
Tire* bmwTire = bmwFactory->createTire();
bmwCar->show();
bmwTire->show();
delete bmwCar;
delete bmwTire;
delete bmwFactory;
// 创建 Audi 工厂
AbstractFactory* audiFactory = new AudiFactory();
Car* audiCar = audiFactory->createCar();
Tire* audiTire = audiFactory->createTire();
audiCar->show();
audiTire->show();
delete audiCar;
delete audiTire;
delete audiFactory;
return 0;
}