单例模式是Java中最常用的模式之一,它通过阻止外部实例化和修改,来控制所创建的对象的数量。这个概念可以被推广到仅有一个对象能更高效运行的系统,或者限制对象实例化为特定的数目的系统中。例如:
- 私有构造函数 - 其他类不能实例化一个新的对象。
- 私有化引用 - 不能进行外部修改。
- 公有静态方法是唯一可以获得对象的方式。
单例模式的故事
来看一下使用情况:一个国家只能有一位总统(可能在正常情况下)。所以不管任何时候我们需要一位总统,使用AmericaPresident就能返回一个。getPresident()方法将确保只有一个总统对象被创建。否者,就不妙了。
类图

单例模式Java示例代码
|
1
2
3
4
5
6
7
8
9
10
11
|
package com.programcreek.designpatterns.singleton;public class AmericaPresident { private AmericaPresident() { } private static final AmericaPresident thePresident=new AmericaPresident(); public static AmericaPresident getPresident(){ return thePresident; }} |
单例模式在 Java 标准库中的使用
java.lang.Runtime#getRuntime() 是Java 标准库中常用的方法,它返回与当前Java应用关联的运行时对象。
下面是getRunTime() 的一个简单例子,它在windows系统上读取一个网页。
|
1
2
3
4
5
6
7
8
9
10
11
12
|
Process p = Runtime.getRuntime().exec( "C:/windows/system32/ping.exe programcreek.com");//get process input stream and put it to buffered readerBufferedReader input = new BufferedReader(new InputStreamReader( p.getInputStream()));String line;while ((line = input.readLine()) != null) { System.out.println(line);}input.close(); |
输出结果
|
1
2
3
4
5
6
7
8
9
|
Pinging programcreek.com [198.71.49.96] with 32 bytes of data:Reply from 198.71.49.96: bytes=32 time=53ms TTL=47Reply from 198.71.49.96: bytes=32 time=53ms TTL=47Reply from 198.71.49.96: bytes=32 time=52ms TTL=47Reply from 198.71.49.96: bytes=32 time=53ms TTL=47Ping 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 |
浙公网安备 33010602011771号