gpt4 book ai didi

c++ - 单例抽象工厂模式

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:20:05 24 4
gpt4 key购买 nike

我想实现一个抽象工厂模式,但也想成为一个单例。

class WindowFactory {
protected:
virtual Scrollbar* createScrollbar() = 0;
};

class MacWindowFactory: public WindowFactory {
virtual Scrollbar* createScrollbar() {
//return a instance
}
;
};

class LinuxWindowFactory: public WindowFactory {
virtual ScrollBar* createScrollbar() {
//return a instance
}
;
};

谁能帮我提供一些制作这个抽象工厂单例的示例代码?

提前致谢。

最佳答案

我想出了更优雅的解决方案(目前没有错误检查)。请让我知道你的想法

#include<iostream>
#include<map>

class AbstractFactory
{
private:
typedef std::map< std::string, AbstractFactory* > ClientMap;
static ClientMap s_clientMap;
public:
void virtual createScrollbar() = 0;
void virtual createWindow() = 0;
static AbstractFactory* createInstance( std::string client );
protected:
void Register( std::string, AbstractFactory* );
};

AbstractFactory::ClientMap AbstractFactory::s_clientMap;

class LinuxFactory: public AbstractFactory
{
public:
void createScrollbar()
{
std::cout<<"Scrollbar for Linux"<<std::endl;
}

void createWindow()
{
std::cout<<"WIndow for Linux"<<std::endl;
}
private:
LinuxFactory()
{
Register( "Linux", this );
}
LinuxFactory( const LinuxFactory& );
static LinuxFactory s_LinuxFactory;

};
LinuxFactory LinuxFactory::s_LinuxFactory;

class MacFactory: public AbstractFactory
{
public:
void createScrollbar()
{
std::cout<<"Scrollbar for Mac"<<std::endl;
}

void createWindow()
{
std::cout<<"WIndow for Mac"<<std::endl;
}

private:
MacFactory()
{
Register( "Mac", this );
}
MacFactory( const MacFactory& );
static MacFactory s_MacFactory;
};
MacFactory MacFactory::s_MacFactory;

void AbstractFactory::Register( std::string clientName, AbstractFactory* factory )
{
s_clientMap.insert( ClientMap::value_type( clientName, factory ) );

}
AbstractFactory* AbstractFactory::createInstance( std::string client )
{
return s_clientMap.find( client )->second;

}

int main()
{
AbstractFactory *factory = AbstractFactory::createInstance( "Linux" );
factory->createScrollbar();
factory->createWindow();
}

关于c++ - 单例抽象工厂模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12661405/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com