Factory Method

Factory Method

 

#include<iostream>
#include<string>

using std::string;
using std::endl;
using std::cout;

class Product{
public:
    virtual string operation()const = 0;
    virtual ~Product(){ }
};

class ConcreteProductA : public Product{
public:
    string operation()const override
    {
        return "operation of ConcreteProductA";
    }
};

class ConcreteProductB : public Product{
public:
    string operation()const override
    {
        return "operation of ConcreteProductB";
    }
};

class Creator{
public:
    virtual ~Creator() { }
    virtual Product* create()const = 0;
    
    string someOperation()const
    {
        Product* p = this->create();
        string ret = "The same creator code works on different products: " + p->operation();
        delete p;
        return ret;
    }
};

class ConcreteCreatorA : public Creator{
public:
    Product* create()const override
    {
        return new ConcreteProductA();
    }
};

class ConcreteCreatorB : public Creator{
public:
    Product* create()const override
    {
        return new ConcreteProductB();
    }
};

void client(const Creator& c)
{
    cout << "The client doesn't know creator's class!" << endl;
    cout << c.someOperation() << endl;
}

int main()
{
    Creator* a = new ConcreteCreatorA;
    Creator* b = new ConcreteCreatorB;
    
    client(*a);
    client(*b);

    delete a, b;

    return 0;
}

 

上一篇:svn报错:“Previous operation has not finished; run 'cleanup' if it was interrupted“ 的解决方法


下一篇:vue npm ERR! Error:EPERM:operation not permitted