来自:https://stackoverflow.com/A/47453161/462608
工厂
想象一下,你正在建造一座房子,你走近一个木匠,想要一扇门。 你将门的尺寸和你所需的量给他,他就为你建造一扇门。 在这种情况下,木匠是一个工厂的门。 你的规格是工厂的输入,门是工厂的输出或产品。
抽象工厂
现在,考虑同样的门的例子。 你可以去找木匠,也可以去塑料门店或PVC店。 都是门厂。 根据情况,你决定你需要接近什么样的工厂。 这就像一个抽象的工厂。
根据那个解释,我不确定下面的代码是工厂方法还是抽象工厂模式?
class PaintShape
{
public:
static PaintShape *createShapeObject( std::string shape );
virtual void print() { std::cout << "print PaintShape"; }
};
class PaintTriangle : public PaintShape
{
public:
PaintTriangle() {}
virtual void print() { std::cout << "\nprint PaintTriangle"; }
};
class PaintRectangle : public PaintShape
{
public:
PaintRectangle() {}
virtual void print() { std::cout << "\nprint PaintRectangle"; }
};
PaintShape* PaintShape::createShapeObject( std::string shape )
{
if( shape == "triangle" )
return new PaintTriangle;
else if( shape == "rectangle" )
return new PaintRectangle;
return new PaintShape;
};
class EndDeveloper
{
public:
EndDeveloper()
{
std::string shape;
std::cout << "\nWhat shape would you like? ";
// Get input from the terminal.
std::getline( std::cin, shape );
PaintShape *p = PaintShape::createShapeObject( shape );
p->print();
std::cout << "\nWhat shape would you like? ";
std::getline (std::cin, shape);
PaintShape *s = PaintShape::createShapeObject( shape );
s->print();
}
};
工厂方法只产生一个项,而抽象工厂产生某种程度上相关项的子集。
在您的示例中,您有一个模式工厂方法
建议如何记住一些解释换句话说,并不是真的对每个人都有效。 对我来说,从引号上看不出有什么区别:)我建议你读下一本书,把东西摆在各自的位置上