Singleton模式是创建模式。
这种模式只涉及一个类是负责创建自己的对象。
该类确保只有单个对象获得创建。
这个类提供一种方法来访问它的唯一对象。
例如,当设计一个用户界面,我们只能有一个主应用程序的窗口。我们可以用单件模式,以确保只有一个的MainApplicationWindow对象的实例。
例
下面的代码将创建一个MainWindow类。
MainWindow类有其私人构造,并有其自身的静态实例。
MainWindow类提供了一个静态方法来获得其静态实例外面的世界。
主,我们的演示类将使用主窗口类来获得一个主窗口对象。
class MainWindow {
//create an object of MainWindow private static MainWindow instance = new MainWindow();
//make the constructor private so that this class cannot be
//instantiated by other class
private MainWindow(){}
//Get the only object available
public static MainWindow getInstance(){
return instance;
} public void showMessage(){
System.out.println("Hello World!");
}
}
public class Main {
public static void main(String[] args) {
//Get the only object available
MainWindow object = MainWindow.getInstance();
//show the message
object.showMessage();
}
}
上面的代码会生成以下结果。