工厂 想象一下,你正在建造一座房子,你走近一位木匠要一扇门。你要为那门和你的需要量出尺度,他就为你建造一扇门。在这种情况下,木匠是一个门工厂。您的规格是工厂的输入,门是工厂的输出或产品。 抽象工厂 现在,考虑同样的门的例子。你可以去木匠,也可以去塑料门店或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();
}
};将如何将其转换为工厂方法和/或抽象工厂方法?
发布于 2020-07-02 15:02:08
工厂方法只生成一个项,而抽象工厂则生成某种相关项的子集。
在您的例子中,您有一个模式工厂方法。
关于如何记住解释过的东西的建议并不适用于每个人。对我来说,从引文中看不出有什么区别:)我建议你阅读以下书籍,把它们放在它们的位置上:
https://stackoverflow.com/questions/62697398
复制相似问题