Java Design Pattern: Singleton

Singleton pattern is one of the most commonly used patterns in Java. It is used to control the number of objects created by preventing external instantiation and modification. This concept can be generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects, such as:

  1. private constructor – no other class can instantiate a new object.
  2. private reference – no external modification.
  3. public static method is the only place that can get an object.

The Story for Singleton

Here is a simple usage case. A country can have only one president (maybe normally). So whenever we want a president, just use AmericaPresident to return one. getPresident() method will make sure there is always only one president created. Otherwise, it would not be so nice.

Class Diagram

singleton

Java Code

 

package com.programcreek.designpatterns.singleton;
 
public class AmericaPresident {
	private AmericaPresident() {	}
 
	private static AmericaPresident thePresident;
 
	public static AmericaPresident getPresident(){
		if(thePresident == null)
			thePresident = new AmericaPresident();
		return thePresident;
	}
} 


 

Singleton Pattern Used in Java Stand Library

java.lang.Runtime#getRuntime() is a frequently used method from Java standard library.getRunTime() returns the runtime object associated with the current Java application.

Here is a simple example of getRunTime(). It reads a webpage on a Windows system.

 

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(); 


Output

 

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 


 

 FROM: http://www.programcreek.com/2011/07/java-design-pattern-singleton/


涉及:创建singleton 类的子类问题:具体参见

Design Pattern: Registry of Singleton 模式

http://www.riabook.cn/doc/designpattern/RegistryOfSingleton.htm


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值