单例模式-双检查锁
class Singleton
{
public:
static Singleton * getinstence()
{
//防止每次都加锁,影响性能
if (NULL == m_instence)
{
Lock();
//防止多线程同时到达加锁处,重复创建实例
if (NULL = m_instence)
m_instence = Singleton();
Unlock();
}
return m_instence;
}
static destroy()
{
if (m_instance)
delete m_instance;
m_instance = NULL;
}
private:
Singleton(){ cout << "sucess"<<endl;:};
static SIngleton *m_instence;
}
//static成员变量需要在类定义体外进行初始化与定义,因为static数据成员独立该类的任意对象存在,它是与类关联的对象,不与类对象关联。
// 提供全局访问点
static Singleton::m_instence = NULL;
int main()
{
Singleton * singleton = getinstence();
return 0;
}
工厂模式
简单工厂
只有产品类,没有工厂类
#include <iostream>
using namespace std;
enum PRODUCTTYPE {SFJ,XSL,NAS};
class soapBase
{
public:
virtual ~soapBase(){};
virtual void show() = 0;
};
class SFJSoap:public soapBase
{
public:
void show() {cout<<"SFJ Soap!"<<endl;}
};
class XSLSoap:public soapBase
{
public:
void show() {cout<<"XSL Soap!"<<endl;}
};
class NASSoap:public soapBase
{
public:
void show() {cout<<"NAS Soap!"<<endl;}
};
class Factory
{
public:
soapBase * creatSoap(PRODUCTTYPE type)
{
switch(type)
{
case SFJ:
return new SFJSoap();
break;
case XSL:
return new XSLSoap();
break;
case NAS:
return new NASSoap();
break;
default:break;
}
}
};
int main()
{
Factory factory;
soapBase* pSoap1 = factory.creatSoap(SFJ);
pSoap1->show();
soapBase* pSoap2 = factory.creatSoap(XSL);
pSoap2->show();
soapBase* pSoap3 = factory.creatSoap(NAS);
pSoap3->show();
delete pSoap1;
delete pSoap2;
delete pSoap3;
return 0;
}
工厂方法
既有产品类,又有工厂类
#include <iostream>
using namespace std;
enum SOAPTYPE {SFJ,XSL,NAS};
class soapBase
{
public:
virtual ~soapBase(){};
virtual void show() = 0;
};
class SFJSoap:public soapBase
{
public:
void show() {cout<<"SFJ Soap!"<<endl;}
};
class XSLSoap:public soapBase
{
public:
void show() {cout<<"XSL Soap!"<<endl;}
};
class NASSoap:public soapBase
{
public:
void show() {cout<<"NAS Soap!"<<endl;}
};
class FactoryBase
{
public:
virtual soapBase * creatSoap() = 0;
};
class SFJFactory:public FactoryBase
{
public:
soapBase * creatSoap()
{
return new SFJSoap();
}
};
class XSLFactory:public FactoryBase
{
public:
soapBase * creatSoap()
{
return new XSLSoap();
}
};
class NASFactory:public FactoryBase
{
public:
soapBase * creatSoap()
{
return new NASSoap();
}
};
int main()
{
SFJFactory factory1;
soapBase* pSoap1 = factory1.creatSoap();
pSoap1->show();
XSLFactory factory2;
soapBase* pSoap2 = factory2.creatSoap();
pSoap2->show();
NASFactory factory3;
soapBase* pSoap3 = factory3.creatSoap();
pSoap3->show();
delete pSoap1;
delete pSoap2;
delete pSoap3;
return 0;
}
区别:由工厂类创建对象而不是由抽象工厂类创建对象