Singleton(單態(tài))
中心思想:是保證在Java應用程序中,一個類Class只有一個實例存在
主要作用:
Singleton 模式主要作用是保證在Java應用程序中,一個類Class只有一個實例存在。
在很多操作中,比如建立目錄 數(shù)據(jù)庫連接都需要這樣的單線程操作。
使用Singleton的好處還在于可以節(jié)省內(nèi)存,因為它限制了實例的個數(shù),有利于Java垃圾回收(garbage collection)。
Singleton 也能夠被無狀態(tài)化。提供工具性質的功能,
具體操作步驟:
1,private構造方法
2,private靜態(tài)成員引用
3,public的靜態(tài)方法提供給外部使用。

2

3

4

5

6

7

8

9

10

11

12

上面是餓漢式,可以多線程。
public class LazySingleton
{
/**
* @label Creates
*/
private static LazySingleton m_instance = null;
private LazySingleton() { }
(synchronized )public static LazySingleton getInstance()
{
if (m_instance == null)
{
m_instance = new LazySingleton();
}
return m_instance;
}
}
只適合單線程的條件下,如果使用多線程的話,那么必須采用synchronized來修飾方法,使得每個線程進入此方法前都要等待別的線程離開此方法。也就是說不會有2個線程同時進入方法。
posted on 2009-04-11 01:46 luofeng225 閱讀(221) 評論(0) 編輯 收藏 所屬分類: 設計模式