Java设计模式:单例

单例模式是Java中最常用的模式之一。它用于通过防止外部实例化和修改来控制创建的对象数。可以将此概念推广到仅存在一个对象的情况下可以更高效地运行的系统,或者将实例化限制为一定数量的对象的系统,例如:

1,私有构造函数-没有其他类可以实例化新对象。
2,私人参考-无需外部修改。
3,公共静态方法是唯一可以获取对象的地方。

辛格尔顿的故事

这是一个简单的用例。一个国家只能有一位总统。因此,每当需要一位总统时,都应该选出唯一的总统,而不是创建新的总统。该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 Stand库中使用的Singleton模式

java.lang.Runtime#getRuntime()是Java标准库中的一种常用方法。getRunTime()返回与当前Java应用程序关联的运行时对象。

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(有效Java)提出了更好的Singleton实现。如果您不熟悉Enum,这是Oracle的一个很好的例子。

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

在这里插入图片描述

发布了0 篇原创文章 · 获赞 0 · 访问量 92

猜你喜欢

转载自blog.csdn.net/qq_41806546/article/details/105136641