设计模式之单例模式(Singleton Pattern)

单例模式

单例模式(Singleton Pattern)在java中算是最常用的设计模式之一,主要用于控制控制类实例的数量,防止外部实例化或者修改。单例模式在某些场景下可以提高系统运行效率。实现中的主要特点有以下三点:

  1. 私有构造函数(private constructor):其他的类不能实例化此类的对象。
  2. 私有化引用(private reference): 类之外不能修改。
  3. 存在唯一的实例化对象的静态方法。

下面以美国只有一个总统的例子对单例模式进行形象化说明。

类图

singleton

代码

 1 package patterns;
 2 
 3 public class AmericaPresident {
 4     
 5     private static AmericaPresident aAmericaPresident;
 6     
 7     private AmericaPresident(){}
 8     
 9     public static AmericaPresident getAmericaPresidentInstance(){
10         if(aAmericaPresident == null)
11             aAmericaPresident = new AmericaPresident();
12         return aAmericaPresident;
13     }
14     
15     public static void testAmericanPresidentInstance(){
16         System.out.println(aAmericaPresident.hashCode());
17     }
18     
19     public static void main(String[] args){
20         AmericaPresident americaPresident_1 = AmericaPresident.getAmericaPresidentInstance();
21         americaPresident_1.testAmericanPresidentInstance();
22         AmericaPresident americaPresident_2 = AmericaPresident.getAmericaPresidentInstance();
23         americaPresident_2.testAmericanPresidentInstance();
24     }
25 }
View Code

输出

580487944

580487944

结论

两次实例化的对象的哈西直相同,说明第二次实例化的事后没有真正的进行实例化,返回的是第一次实例化的对象。

原文地址:https://www.cnblogs.com/RobertC/p/3495882.html