- 論壇徽章:
- 0
|
快畢業(yè)了,最近一直找了一段時間的工作,參加了很多公司的面試,發(fā)現(xiàn)大公司對設計模式都比較感興趣,都問了我設計模式相關的東西,所以這段時間復習了一下設計模式,并做了一個總結(jié), 想和大家一起復習一下設計模式,歡迎大家補充和討論:
一、 單例(Singleton)模式
單例模式的特點:
單例類只能有一個實例。
單例類必須自己創(chuàng)建自己的唯一實例。
單例類必須給所有其它對象提供這一實例。
單例模式應用:
每臺計算機可以有若干個打印機,但只能有一個Printer Spooler,避免兩個打印作業(yè)同時輸出到打印機。
一個具有自動編號主鍵的表可以有多個用戶同時使用,但數(shù)據(jù)庫中只能有一個地方分配下一個主鍵編號。否則會出現(xiàn)主鍵重復。
二、 Singleton模式的結(jié)構(gòu):
Singleton模式包含的角色只有一個,就是Singleton。Singleton擁有一個私有構(gòu)造函數(shù),確保用戶無法通過new直接實例它。除此之外,該模式中包含一個靜態(tài)私有成員變量instance與靜態(tài)公有方法Instance()。Instance方法負責檢驗并實例化自己,然后存儲在靜態(tài)成員變量中,以確保只有一個實例被創(chuàng)建。(關于線程問題以及C#所特有的Singleton將在后面詳細論述)。
三、 在什么情形下使用單例模式:
使用Singleton模式有一個必要條件:在一個系統(tǒng)要求一個類只有一個實例時才應當使用單例模式。反過來,如果一個類可以有幾個實例共存,就不要使用單例模式。
注意:
不要使用單例模式存取全局變量。這違背了單例模式的用意,最好放到對應類的靜態(tài)成員中。
不要將數(shù)據(jù)庫連接做成單例,因為一個系統(tǒng)可能會與數(shù)據(jù)庫有多個連接,并且在有連接池的情況下,應當盡可能及時釋放連接。Singleton模式由于使用靜態(tài)成員存儲類實例,所以可能會造成資源無法及時釋放,帶來問題。
四.Singleton的代碼實現(xiàn)
(1)C++版本
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *Instance()
{
if (NULL == _instance)
{
_instance = new Singleton();
}
return _instance;
}
void method1(){cout << " method1 is done~ " << endl;};
protected:
Singleton(void){ cout <<" Singleton() " << endl;};
virtual ~Singleton(){cout << "~singletont()" <<endl; }
static Singleton* _instance;
};
//static 變量需要在類定義外面進行初始化
Singleton* Singleton::_instance = NULL;
int main()
{
cout << "Hello, world~!" << endl;
Singleton::Instance()->method1();
Singleton::Instance()->method1();
return 0;
} |
(2) C#版本
sealed class Singleton
{
private Singleton();
public static readonly Singleton Instance = new Singleton();
}
//實現(xiàn)延遲初始化
public sealed class Singleton
{
Singleton()
{
}
public static Singleton GetInstance()
{
return Nested.instance;
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
|
(3)JAVA版本
Public class Singleton{
private static Singleton uniqueInstance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// other useful methods here
}
/*這種寫法可以實現(xiàn)單件模式,既簡單又有效,利用了synchronized的同步方法。但是會帶來嚴重的性能問題。同步一個方法可能造成程序執(zhí)行效率下降100倍。因此,如果將getInstance()放到頻繁運行的地方,就要重新考慮自己的設計了。
*/
|
五參考資料
1.http://www.cppblog.com/SoRoMan/a ... 0140.html?opt=admin
2. http://leo-faith.javaeye.com/blog/177779
[ 本帖最后由 scuwb 于 2008-10-28 20:58 編輯 ] |
評分
-
查看全部評分
|