5,530
社区成员
发帖
与我相关
我的任务
分享
m_mapInst[nSytle1] = new CStyle1;
m_mapInst[nSytle2] = new CStyle2;
m_mapInst[nSytle3] = new CStyle3;
m_mapInst[nSytle4] = new CStyle4;
m_mapInst[nSytle5] = new CStyle5;
工厂模式是将对象的实例化延迟到子类,工厂根据类型创建子类对象 有两种方法 传参和模板
单例模式是一个类有且只有一个实例
#include <iostream>
#include <string>
//抽象基类定义调用接口
class Base
{
public:
Base(){}
virtual ~Base(){} //防止内存泄漏 必须为virtual
virtual void print()=0;
};
class Derived_1: public Base
{
public:
void print()
{
std::cout<<"derived_1.print()"<<std::endl;
}
};
class Derived_2 : public Base
{
public:
void print()
{
std::cout<<"derived_2.print()"<<std::endl;
}
};
//工厂模式 模板创建法
template < typename T >
class Factory
{
public:
Factory(){}
Base* Create()
{
m_pBase = new T();
return m_pBase;
}
~Factory()
{
delete m_pBase;
}
private:
Base* m_pBase;
};
//工厂模式 类型创建
class TypeFactory
{
public:
TypeFactory(){}
virtual ~TypeFactory()
{
delete m_pBase;
}
Base* Create(std::string type)
{
if( type == "Derived_1")
{
m_pBase = new Derived_1();
}
else
{
m_pBase = new Derived_2();
}
return m_pBase;
}
private:
Base* m_pBase;
};
//单例模式
class Singleton
{
public:
static Singleton* Instance()
{
if( m_instance == 0)
{
m_instance = new Singleton();
}
return m_instance;
}
void AddCount()
{
std::cout<<"count:"<<count<<std::endl;
count++;
}
protected:
Singleton():count(0){} //无法通过外部访问 只有Instance接口创建
private:
static Singleton* m_instance; //全局唯一
int count;
};
Singleton* Singleton::m_instance = 0;
int main()
{
//模板调用方法
Factory<Derived_1> fd1;
Factory<Derived_2> fd2;
std::cout<<"template method:"<<std::endl;
fd1.Create()->print();
fd2.Create()->print();
//类型参数
TypeFactory tf;
std::cout<<"Type method:"<<std::endl;
tf.Create("Derived_1")->print();
tf.Create("Derived_2")->print();
//单例模式
Singleton *pSingle = Singleton::Instance();
pSingle->AddCount();
pSingle->AddCount();
return 0;
}
factory(Sytle1,1) = m_mapInst[nSytle11] = new CStyle1;
factory(Sytle1,2) = m_mapInst[nSytle12] = new CStyle1;
factory(Sytle2,1) = m_mapInst[nSytle21] = new CStyle2;
factory(Sytle2,2) = m_mapInst[nSytle22] = new CStyle2;
......
style1 = factory(Sytle1) = new CStyle1;
style2 = factory(Sytle2) = new CStyle2;
Destroy(style1 );
Destroy(style2 );