C++单例抽象工厂模式

#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>

using namespace std;

class Scrollbar;

class WindowFactory {
public:
    static void setFactory(std::string const&);
    static Scrollbar* createScrollbar();
    virtual ~WindowFactory() {}
private:
    virtual Scrollbar* doCreateScrollbar() = 0;
};

class MacWindowFactory
    : public WindowFactory {
public :
    friend void WindowFactory::setFactory(std::string const&);
    virtual Scrollbar* doCreateScrollbar() {
        return 0;
    }
};

class LinuxWindowFactory
    : public WindowFactory {
    friend void WindowFactory::setFactory(std::string const&);
    virtual Scrollbar* doCreateScrollbar() {
        return 0;
    }
};

// in WindowFactory.cpp

static std::auto_ptr<WindowFactory>& getPointer()
{
    static std::auto_ptr<WindowFactory> pointer;
    return pointer;
}

Scrollbar* WindowFactory::createScrollbar()
{
    return getPointer().get()
        ? getPointer()->doCreateScrollbar()
        : throw std::runtime_error("WindowFactory not set");
}

void WindowFactory::setFactory(std::string const& what)
{
    if (what == "Mac") {
        getPointer() = std::auto_ptr<WindowFactory>(new MacWindowFactory());
    }
    else if (what == "Linux") {
        getPointer() = std::auto_ptr<WindowFactory>(new LinuxWindowFactory());
    }
    else {
        throw std::runtime_error("unknown factory: '" + what + "'");
    }
}


int main()
{
    cout << "Hello world!" << endl;
    MacWindowFactory macWindowFactory;
    macWindowFactory.setFactory("Mac");
    int a = (int)macWindowFactory.createScrollbar();
    cout << a;
    return 0;
}

你可能感兴趣的:(读书笔记,c++,设计模式)