单例类

如果一个类始终只能创建一个实例,

 

 1 class Singleton {
 2     public static Singleton instance;
 3     private Singleton() {}
 4     public static Singleton getInstance() {
 5         if (instance == null) {
 6             instance = new Singleton();
 7         }
 8 
 9         return instance;
10     }
11 }
12 
13 public class SingletonTest {
14     public static void main(String[] args) {
15         Singleton s1 = Singleton.getInstance();
16         Singleton s2 = Singleton.getInstance();
17 
18         System.out.println(s1 == s2);
19     }
20 }

使用单例类模式

 

posted @ 2018-08-03 11:57  gyhuminyan  阅读(150)  评论(0编辑  收藏  举报