一、介绍
单例模式是一种比较普遍和简单的模式,在我们的程序中经常会用到。简单的说就是,单例模式就是让一个类永远只对外发布唯一的实例(Instance)。
二、实例
在本模式中介绍的例子中,SingleSpoon类拥有一个实例,声明为静态(static)私有(private)变量"theSpoon",核心代码内容如下:
public class SingleSpoon {
private static SingleSpoon theSpoon;
private SingleSpoon() {}
public static SingleSpoon getTheSpoon() {
if (theSpoon == null) {
theSpoon = new SingleSpoon();
}
return theSpoon;
}
public String toString() {
return "Behold the glorious single spoon!";
}
}
单例模式的实际运用的代码如下:
class TestSingleSpoon {
public static void main(String[] args) {
System.out.println("First person getting the spoon");
SingleSpoon spoonForFirstPerson =
SingleSpoon.getTheSpoon();
if (spoonForFirstPerson != null)
System.out.println(spoonForFirstPerson);
else
System.out.println("No spoon was available");
System.out.println("");
System.out.println("Second person getting a spoon");
SingleSpoon spoonForSecondPerson = SingleSpoon.getTheSpoon();
if (spoonForSecondPerson != null)
System.out.println(spoonForSecondPerson);
else
System.out.println("No spoon was available");
}
}
三、分析
创建一个单例模式,需要注意的是:
1、实例变量应该是静态的私有的。
2、外部调用该实例时,不是通过类的构造方法,而是通过一个getInstance()这样的静态方法来创建该类的唯一实例。
3、默认的构造方法应该是私有的,没有强行规定,但觉得这样子自绝后路的办法未尝不可取 :P
4、单例模式并不是线程安全的,要实现这一点,必须在getTheSpoon()方法前面添加一个同步关键字synchronized。