C++实现一个简单工厂模式和抽象工厂模式
时间: 2024-05-01 12:19:48 浏览: 106
简单工厂模式:
简单工厂模式是一个工厂类根据传入的参数决定创建出哪一种产品类的实例。具体实现如下:
```cpp
#include <iostream>
using namespace std;
// 抽象产品类
class Product {
public:
virtual void Show() = 0;
};
// 具体产品类 A
class ProductA : public Product {
public:
void Show() override {
cout << "ProductA" << endl;
}
};
// 具体产品类 B
class ProductB : public Product {
public:
void Show() override {
cout << "ProductB" << endl;
}
};
// 工厂类
class Factory {
public:
Product* CreateProduct(int type) {
switch (type) {
case 0:
return new ProductA();
case 1:
return new ProductB();
default:
return nullptr;
}
}
};
int main() {
Factory factory;
Product* productA = factory.CreateProduct(0);
Product* productB = factory.CreateProduct(1);
productA->Show();
productB->Show();
delete productA;
delete productB;
return 0;
}
```
抽象工厂模式:
抽象工厂模式是一个工厂接口可以创建多个产品类的实例,而具体工厂类实现了工厂接口并能创建多个具体产品类的实例。具体实现如下:
```cpp
#include <iostream>
using namespace std;
// 抽象产品类A
class ProductA {
public:
virtual void Show() = 0;
};
// 具体产品类A1
class ProductA1 : public ProductA {
public:
void Show() override {
cout << "ProductA1" << endl;
}
};
// 具体产品类A2
class ProductA2 : public ProductA {
public:
void Show() override {
cout << "ProductA2" << endl;
}
};
// 抽象产品类B
class ProductB {
public:
virtual void Show() = 0;
};
// 具体产品类B1
class ProductB1 : public ProductB {
public:
void Show() override {
cout << "ProductB1" << endl;
}
};
// 具体产品类B2
class ProductB2 : public ProductB {
public:
void Show() override {
cout << "ProductB2" << endl;
}
};
// 抽象工厂类
class Factory {
public:
virtual ProductA* CreateProductA() = 0;
virtual ProductB* CreateProductB() = 0;
};
// 具体工厂类1
class Factory1 : public Factory {
public:
ProductA* CreateProductA() override {
return new ProductA1();
}
ProductB* CreateProductB() override {
return new ProductB1();
}
};
// 具体工厂类2
class Factory2 : public Factory {
public:
ProductA* CreateProductA() override {
return new ProductA2();
}
ProductB* CreateProductB() override {
return new ProductB2();
}
};
int main() {
Factory* factory1 = new Factory1();
ProductA* productA1 = factory1->CreateProductA();
ProductB* productB1 = factory1->CreateProductB();
productA1->Show();
productB1->Show();
Factory* factory2 = new Factory2();
ProductA* productA2 = factory2->CreateProductA();
ProductB* productB2 = factory2->CreateProductB();
productA2->Show();
productB2->Show();
delete factory1;
delete factory2;
delete productA1;
delete productB1;
delete productA2;
delete productB2;
return 0;
}
```
阅读全文