设计模式之单例模式(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值