您的位置:首页 > 其它

单例模式

2016-02-22 15:03 337 查看
单例模式:

确保一个类只有一个实例,并提供一个全局访问点。

单例模式类图:



经典单例模式实现:

class Singleton{
private:
static Singleton *uniqueInstance;
Singleton(){}
public:
static Singleton *getInstance(){
if (uniqueInstance == NULL) uniqueInstance = new Singleton();
return uniqueInstance;
}
};
下面来看如何将一个普通的巧克力工厂类转为单例类:

class ChocolateBoiler{
private:
bool empty;
bool boiled;
public:
ChocolateBoiler(){//这是原来的构造函数
empty = true;
boiled = false;
}
void fill(){
if (isEmpty()){
empty = false;
boiled = false;
}
}
void drain(){ //排出煮沸的巧克力和牛奶
if (!isEmpty() && isBoiled()) empty = true;
}
void boil(){//加热
if (!isEmpty() && !isBoiled()) boiled = true;
}
bool isEmpty(){
return empty;
}
bool isBoiled(){
return boiled;
}
};
改成单例类后如下:

class ChocolateBoiler{
private:
static ChocolateBoiler *uniqueInstance;  //*
bool empty;
bool boiled;
ChocolateBoiler(){//*这是新的构造函数
empty = true;
boiled = false;
}
public:
static ChocolateBoiler *getInstance(){//*
if (uniqueInstance == NULL) uniqueInstance = new ChocolateBoiler();
return uniqueInstance;
}

void fill(){
if (isEmpty()){
empty = false;
boiled = false;
}
}
void drain(){ //排出煮沸的巧克力和牛奶
if (!isEmpty() && isBoiled()) empty = true;
}
void boil(){//加热
if (!isEmpty() && !isBoiled()) boiled = true;
}
bool isEmpty(){
return empty;
}
bool isBoiled(){
return boiled;
}
};


上面的经典单例模式存在多线程安全问题,解决方法参考面试题2:实现单例模式(offer)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: