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

时间:2023-03-08 19:14:26
设计模式之单例模式(Singleton Pattern)

单例模式

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

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

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

类图

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

代码

 package patterns;

 public class AmericaPresident {

     private static AmericaPresident aAmericaPresident;

     private AmericaPresident(){}

     public static AmericaPresident getAmericaPresidentInstance(){
if(aAmericaPresident == null)
aAmericaPresident = new AmericaPresident();
return aAmericaPresident;
} public static void testAmericanPresidentInstance(){
System.out.println(aAmericaPresident.hashCode());
} public static void main(String[] args){
AmericaPresident americaPresident_1 = AmericaPresident.getAmericaPresidentInstance();
americaPresident_1.testAmericanPresidentInstance();
AmericaPresident americaPresident_2 = AmericaPresident.getAmericaPresidentInstance();
americaPresident_2.testAmericanPresidentInstance();
}
}

输出

580487944

580487944

结论

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