JAVA 單態模式(餓漢式 懶漢式)

//1餓漢式
class Single {

 private static final Single s = new Single();

 private Single() {
 }

 public static Single getInstance() {
  return s;
 }

}

// final 強烈推薦
// -------------------------------------------
// 2.方法2 懶漢式

class Single {
 private static Single s = null;

 private Single() {
 }

 public static Single getInstance() {
  if (s == null) {
   s = new Single();// 延遲加載
  }

  return s;
 }
}

// 如果是單線程這樣是可以的,多線程有安全隱患
// 3-------------------------------------------

class Single {
 public static Single s = null;

 private Single() {
 }

 public static synchronized Single getInstance() {
  if (s == null) {
   s = new Single();
  }

  return s;
 }
}

// 上面這種方法 效率太慢!

// 4---------------------------------------------

class Single {
 public static Single s = null;

 private Single() {
 }

 public static Single getInstance() {
  if (s == null) {

   synchronized (Single.class) {
    if (s == null) {
     s = new Single();
    }
   }
  }

  return s;
 }
}

 

第一種和第四種都是可以的,但是還是推薦第一種!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章