当我们想实例化一个类,并可以一直使用这个类,可以使用单例模式:
方式一:
1 package com.kunhong.design.test; 2 3 public class Singleton { 4 private static Singleton instance = new Singleton(); 5 6 private Singleton() { 7 8 } 9 10 public static Singleton getInstance() {11 return instance;12 }13 }
方法二:
1 package com.kunhong.design.test; 2 3 public class Singleton { 4 private static Singleton instance = null; 5 6 private Singleton() { 7 8 } 9 public synchronized static Singleton getInstance(){10 if(instance == null){11 instance = new Singleton();12 }13 return instance;14 }15 }