创建型模式之一:单例模式

这是设计模式的一系列文章。我将逐一翻译。 系列地址: http://www.programcreek.com/java-design-patterns-in-stories/ 单例模式是Java中最常用的模式,它通过预防外部实例化与修改用来控制对象数量。这个概念可以推广到系统中,当仅有一个对象,或者限制对象在一定数量之中,操作会会更高效。比如: 

1、私有构造器 - 没有一个其他类能实例化一个新对象。 

2、私有引用 - 没有外部的修改 

3、Public级别的方法是唯一获取对象的地方。

单例模式的故事

这里有一个简单的用例:一个国家只能有一个总统,所以,无论哪里需要一个总统,都只能返回仅有的那个总统,而不能去新建一个。getPresident()方法会确定永远只创建一个总统。

类图与代码

 

渴望模式:

public class AmericaPresident {
 private static final AmericaPresident thePresident = new AmericaPresident();
 
 private AmericaPresident() {}
 
 public static AmericaPresident getPresident() {
 return thePresident;
 }
}

thePresident被定义成final类型,所以它永远都包含同一个对象引用。 

懒惰模式:

public class AmericaPresident {
 private static AmericaPresident thePresident;
 
 private AmericaPresident() {}
 
 public static AmericaPresident getPresident() {
 if (thePresident == null) {
 thePresident = new AmericaPresident();
 }
 return thePresident;
 }
}

单例模式在Java标准库中

java.lang.Runtime#getRuntime()方法是Java标准库中频繁使用的方法,getRunTime()方法返回一个与当前Java应用相关的Runtime对象。

class Runtime {
 private static Runtime currentRuntime = new Runtime();
 
 public static Runtime getRuntime() {
 return currentRuntime;
 }
 
 private Runtime() {}
 
 //... 
}

这一个使用getRuntime()的简单例子,它在Windows系统中读取一个网页。

Process p = Runtime.getRuntime().exec(
		"C:/windows/system32/ping.exe programcreek.com");
//get process input stream and put it to buffered reader
BufferedReader input = new BufferedReader(new InputStreamReader(
		p.getInputStream()));
 
String line;
while ((line = input.readLine()) != null) {
	System.out.println(line);
}
 
input.close();

输出:

Pinging programcreek.com [198.71.49.96] with 32 bytes of data:
Reply from 198.71.49.96: bytes=32 time=53ms TTL=47
Reply from 198.71.49.96: bytes=32 time=53ms TTL=47
Reply from 198.71.49.96: bytes=32 time=52ms TTL=47
Reply from 198.71.49.96: bytes=32 time=53ms TTL=47

Ping statistics for 198.71.49.96:
 Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
 Minimum = 52ms, Maximum = 53ms, Average = 52ms

另外一种单例模式的实现

私有的构造器在反射中没有保护实例化, Joshua Bloch (Effective Java) 提供了一种更好的实现方法。如果你还不熟悉枚举,这是有一个Oraclekh提供的好的例子

public enum AmericaPresident{
 INSTANCE;
 
 public static void doSomething(){
 //do something
 }
}

以上文章翻译自: http://www.programcreek.com/2011/07/java-design-pattern-singleton/

转载于:https://my.oschina.net/markho/blog/498167

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值