抽象工厂模式介绍
抽象工厂模式是一种创建型设计模式,它提供了一种创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。它允许客户端使用抽象接口来创建一组相关的对象,而不必关心它们的具体实现。
抽象工厂模式通常用于以下情况:
- 系统需要独立于它的产品的创建、组合和表示时。
- 系统需要由多个系列中的一个来配置时。
- 需要强调一组相关产品对象的设计以便进行联合使用时。
- 提供一个产品类库,而只想显示它们的接口而不是实现时。
C++代码具体实现
#include <iostream>
class Fruit{
public:
virtual ~Fruit(){}
virtual void color() = 0;
};
class Apple : public Fruit{
public:
void color() override{
std::cout << "Apple::pink" << std::endl;
}
};
class Orange : public Fruit{
public:
void color() override{
std::cout << "Orange::yellow" << std::endl;
}
};
class Vegetable{
public:
virtual~Vegetable(){}
virtual void size() = 0;
};
class Cucumber : public Vegetable{
public:
void size() override{
std::cout << "12px" << std::endl;
}
};
class Tomato : public Vegetable{
public:
void size() override{
std::cout << "10px" << std::endl;
}
};
class Factory{
public:
virtual ~Factory(){}
virtual Fruit* createFruit() = 0;
virtual Vegetable* createVegetable() = 0;
};
class FactoryA : public Factory{
public:
Fruit* createFruit(){
return new Apple();
}
Vegetable* createVegetable(){
return new Cucumber();
}
};
class FacotryB : public Factory{
public:
Fruit* createFruit(){
return new Orange();
}
Vegetable* createVegetable(){
return new Tomato();
}
};
int main(int argc, char* argv[]){
Factory* factory1 = new FactoryA();
Fruit* apple = factory1->createFruit();
Vegetable* cucumber = factory1->createVegetable();
apple->color();
cucumber->size();
delete factory1;
delete apple;
delete cucumber;
Factory* factory2 = new FacotryB();
Fruit* orange = factory2->createFruit();
Vegetable* tomato = factory2->createVegetable();
orange->color();
tomato->size();
delete factory2;
delete orange;
delete tomato;
}