設計模式之Singleton單態,設計模式singleton

來源:互聯網
上載者:User

設計模式之Singleton單態,設計模式singleton
1.概念

1.在Java應用程式中,一個類Class只能有一個執行個體存在

2.一個執行個體

1) 私人的構造方法

2) 私人的靜態執行個體

3) 公有靜態訪問方式

1) 防止建立新的執行個體

2) 防止修改

3) 必需能夠擷取

public class Singleton {// 1.私人的構造方法private Singleton() {}// 2.私人的靜態執行個體變數private static Singleton sl = new Singleton();// 3.公有靜態存取方法public static Singleton getsingleton() {return sl;}}
1.惡漢與懶漢

1.惡漢

一開始就建立對象

1)提前建立對象

2.懶漢

有需求就建立對象

1)使用方法時才建立對象

3.惡漢

4.懶漢

public class badmash {// 1.私人的構造方法private badmash() {}// 2.私人的靜態執行個體變數private static badmash bmBadmash = new badmash();// 3.公有的靜態存取方法public static badmash getBadmash() {return bmBadmash;}}
public class sluggard {// 1.私人的構造方法private sluggard() {}// 2.私人的靜態變數執行個體private static sluggard sg = null;// 3.公有的靜態存取方法public static sluggard getSluggard() {if (sg == null) {sg = new sluggard();}return sg;}}

1) 惡漢是安全執行緒的

1) 懶漢線程是不安全的

1.安全執行緒

1) 線程同步的作用:把代碼控制,讓線程排隊執行、

同步關鍵字

同步代碼塊

public class sluggard_synchro {

// 1.私人的構造方法

private sluggard_synchro() {

 

}

 

// 2.私人的靜態變數執行個體

private static sluggard_synchro sg = null;

 

// 3.公有的靜態存取方法

public static synchronized sluggard_synchro getSluggard() {

if (sg == null) {

sg = new sluggard_synchro();

}

return sg;

}

}

public class sluggard_code {

// 1.私人的構造方法

private sluggard_code() {

 

}

 

// 2.私人的靜態變數執行個體

private static sluggard_code sg = null;

 

// 3.公有的靜態存取方法

final private static Object OBJECT = new Object();

 

public static sluggard_code getSluggard() {

synchronized (OBJECT) {

if (sg == null) {

sg = new sluggard_code();

}

}

return sg;

}

}

效率偏低

4.雙重鎖

 

public class sluggard_bilayer {

// 1.私人的構造方法

private sluggard_bilayer() {

 

}

 

// 2.私人的靜態變數執行個體

private static sluggard_bilayer sg = null;

 

// 3.公有的靜態存取方法

final private static Object OBJECT = new Object();

 

public static sluggard_bilayer getSluggard() {

if (sg == null) {// 條件1

synchronized (OBJECT) {

if (sg == null) {// 條件2

sg = new sluggard_bilayer();

}

}

}

return sg;

}

}

 

註:Android系統層級的服務通常都是一個執行個體的設計,即單例。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.