说明:
工厂模式(Factory Pattern)是创建型模式,它提供了一种创建对象的最佳方式。 在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口(工厂)来指向新创建的对象。
主要解决:主要解决接口选择的问题。
何时使用:我们明确地计划不同条件下创建不同实例时。
如何解决:让其子类实现工厂接口,返回的也是一个抽象的产品。
关键代码:创建过程在其子类执行。
DEMO:
class Fruit {
public:
virtual void eat() = 0;
};
class Banana :public Fruit
{
public:
void eat(){ printf("eat banana"); }
};
class Apple :public Fruit
{
public:
void eat(){ printf("eat apple"); }
};
class Fruitsfactory {
public:
static Fruit* getFruits(QString type) {
Fruit* f = nullptr;
if (type == "apple") {
f = new Apple();
}
else if (type == "banana"){
f = new Banana();
}
return f;
}
};
调用:
Fruit* a = Fruitsfactory::getFruits("apple");
a->eat();
Fruit* b = Fruitsfactory::getFruits("banana");
b->eat();
输出结果: