1。多用组合,少用继承。多利用多态,重载,运行时确定类型的特性去设计类。
//----Singleton.H---
//云中哈哈
class Singleton

...{
public:
static Singleton* Instance(); //生成对象
protected:
Singleton(); //此设计此调用方不能用NEW去生成对象。起到了保护对象的作用
private:
static Singleton* _instance; //对象句柄
};
//----Singleton.cpp---
//云中哈哈
//2007-12-11
Singleton* Singleton::_instance = 0;

Singleton::Singleton()

...{
cout<<"Singleton...."<<endl;
}

Singleton* Singleton::Instance()

...{
if (_instance == 0)

...{
_instance = new Singleton(); // 此只生成一次对象!
}
return _instance;
}
//----MAIN.CPP
//云中哈哈
//2007-12-11
#include "Singleton.h"
#include <iostream>
using namespace std;

int main(int argc,char* argv[])

...{
Singleton* sgn = Singleton::Instance();
Singleton* sgn2 = Singleton::Instance(); //本次会通过但无效果。因为只能构造一次!
//Singleton* sgn3 = new Singleton(); //本句会出错。这样就不能用NEW去生成对象了!
return 0;
}
2。对于只能构造一次的对象。并且对上层隐藏细节。不管其调用几次。都只会生成一次。例如:动态库封装的用户线程对象,全局唯一对象等。
类可以这样设计:
//----Singleton.H---
//云中哈哈
class Singleton 
...{
public:
static Singleton* Instance(); //生成对象
protected:
Singleton(); //此设计此调用方不能用NEW去生成对象。起到了保护对象的作用
private:
static Singleton* _instance; //对象句柄
};
//----Singleton.cpp---
//云中哈哈
//2007-12-11
Singleton* Singleton::_instance = 0;
Singleton::Singleton() 
...{
cout<<"Singleton...."<<endl;
}
Singleton* Singleton::Instance() 
...{
if (_instance == 0) 
...{
_instance = new Singleton(); // 此只生成一次对象!
}
return _instance;
}
//----MAIN.CPP
//云中哈哈
//2007-12-11
#include "Singleton.h"
#include <iostream>
using namespace std;
int main(int argc,char* argv[]) 
...{
Singleton* sgn = Singleton::Instance();
Singleton* sgn2 = Singleton::Instance(); //本次会通过但无效果。因为只能构造一次!
//Singleton* sgn3 = new Singleton(); //本句会出错。这样就不能用NEW去生成对象了!
return 0;
}
本文介绍了一种推荐的设计模式——单例模式,并通过具体实现展示了如何确保类的对象全局唯一且延迟加载。同时强调了面向对象设计中应多使用组合而非继承的原则。
&spm=1001.2101.3001.5002&articleId=1930409&d=1&t=3&u=dc14f8c403e646188d4f25bdf584ff7c)
1370

被折叠的 条评论
为什么被折叠?



