Singleton模式在Java中是一个最常用的模式。它是用来防止通过外部控制创建的对象实例化。这个概念可以推广到系统时更有效率地运作只存在一个对象或对象的实例化限制在一定数量,例如:
1.私有构造函数-没有其他的类可以实例化一个新对象。
2.属性私有化。
3.唯一获取对象,通过静态公共方法获取。
Class Diagram and Code
第一种:
public class AmericaPresident {
private static final AmericaPresident thePresident = new AmericaPresident(); private AmericaPresident() {} public static AmericaPresident getPresident() {
return thePresident;
}}
第二种:
public class AmericaPresident {
private static AmericaPresident thePresident; private AmericaPresident() {} public static AmericaPresident getPresident() {
if (thePresident == null) {
thePresident = new AmericaPresident();
}
return thePresident;
}}
第三种:
public enum AmericaPresident{
INSTANCE; public static void doSomething(){
//do something
}}