jeudi 2 juillet 2020

Is this code factory method or abstract factory pattern?

From: https://stackoverflow.com/a/47453161/462608

Factory

Imagine you are constructing a house and you approach a carpenter for a door. You give the measurement for the door and your requirements, and he will construct a door for you. In this case, the carpenter is a factory of doors. Your specifications are inputs for the factory, and the door is the output or product from the factory.

Abstract Factory

Now, consider the same example of the door. You can go to a carpenter, or you can go to a plastic door shop or a PVC shop. All of them are door factories. Based on the situation, you decide what kind of factory you need to approach. This is like an Abstract Factory.

According to that explanation, I am not sure whether the following code is factory method or abstract factory pattern?

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();
    }
};

Aucun commentaire:

Enregistrer un commentaire