给出简单工厂模式,工厂方法模式,抽象工程模式的c++实例
时间: 2024-10-22 21:28:57 浏览: 20
简单工厂模式、工厂模式、抽象工厂模式案例(C++实现)
5星 · 资源好评率100%
简单工厂模式(Simple Factory Pattern)允许你创建一系列相关或相互依赖的对象,而无需指定它们的确切类。以下是一个简单的C++例子:
```cpp
// 抽象产品类
class Product {
public:
virtual ~Product() {}
virtual void operation() = 0;
};
// 具体产品类
class ConcreteProductA : public Product {
public:
void operation() override { std::cout << "ConcreteProductA is doing something." << std::endl; }
};
class ConcreteProductB : public Product {
public:
void operation() override { std::cout << "ConcreteProductB is doing something different." << std::endl; }
};
// 简单工厂类
class SimpleFactory {
public:
static Product* createProduct(const std::string& type) {
if (type == "A") return new ConcreteProductA();
else if (type == "B") return new ConcreteProductB();
else throw std::invalid_argument("Invalid product type.");
}
};
```
工厂方法模式(Factory Method Pattern)提供了一种创建对象的最佳方式,但让子类可以决定由哪个类实例化。举个例子:
```cpp
// 抽象工厂接口
class Factory {
public:
virtual ~Factory() {}
virtual Product* getProduct(const std::string& type) = 0;
};
// 具体工厂类
class ConcreteFactoryA : public Factory {
public:
Product* getProduct(const std::string& type) override {
if (type == "A") return new ConcreteProductA();
else throw std::invalid_argument("Invalid product type in factory A.");
}
};
class ConcreteFactoryB : public Factory {
public:
Product* getProduct(const std::string& type) override {
if (type == "B") return new ConcreteProductB();
else throw std::invalid_argument("Invalid product type in factory B.");
}
};
// 客户端代码
void useProduct(Factory* factory) {
Product* product = factory->getProduct("A"); // 使用工厂生产的对象
product->operation();
}
int main() {
Factory* factoryA = new ConcreteFactoryA();
useProduct(factoryA);
delete factoryA;
Factory* factoryB = new ConcreteFactoryB();
useProduct(factoryB);
delete factoryB;
return 0;
}
```
抽象工程模式(Abstract Factory Pattern)则更复杂一些,它提供了一个接口,用于创建一系列相关的对象,这些对象属于一个产品族,并且它们必须共同遵守一个不变的主题。由于篇幅较长,这里简化展示:
```cpp
// 抽象工厂
class AbstractFactory {
public:
virtual ~AbstractFactory() {}
virtual ProductA* createProductA() = 0;
virtual ProductB* createProductB() = 0;
};
// 具体工厂
class ConcreteFactoryA : public AbstractFactory {
public:
ProductA* createProductA() override { return new ConcreteProductA(); }
ProductB* createProductB() override { return new ConcreteProductB(); }
};
// 抽象产品接口
class ProductA {
public:
virtual ~ProductA() {}
virtual void operationA() = 0;
};
class ProductB {
public:
virtual ~ProductB() {}
virtual void operationB() = 0;
};
// 客户端代码
void useFactory(AbstractFactory* factory) {
ProductA* a = factory->createProductA();
ProductB* b = factory->createProductB();
a->operationA();
b->operationB();
}
int main() {
AbstractFactory* factoryA = new ConcreteFactoryA();
useFactory(factoryA);
delete factoryA;
// 更换工厂...
// ...
return 0;
}
```
阅读全文