Singleton模式是创建模式。
这种模式只涉及一个类是负责创建自己的对象。
该类确保只有一个对象获得创建。
这个类提供了一种方法来访问它的唯一对象。
例如,当设计一个用户界面,我们只能有一个主应用程序的窗口。我们可以使用Singleton模式,以确保有是MainApplicationWindow对象的一个实例。
下面的代码将创建一个主窗口类。
MainWindow类有其私有的构造,并有其自身的静态实例。
主窗口类提供了一个静态方法来获取其静态实例外面的世界。
我们的演示类将使用主窗口类来获得一个主窗口对象。
class MainWindow {
//create an 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 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 available
MainWindow = MainWindow.getInstance();
//show the message
.showMessage();
}
}
继续阅读与本文标签相同的文章
-
城市数字化后,新一代内生安全系统可全方位保护
2026-05-14栏目: 教程
-
谷歌也来“唱衰”5G,5G手机只会徒增功耗?为何这么说?
2026-05-14栏目: 教程
-
量子信息和量子技术白皮书合肥宣言在中科大发布
2026-05-14栏目: 教程
-
微信悄悄更新一新功能,来看看!
2026-05-14栏目: 教程
-
打破三大运营商垄断,第四大运营商终于来了!
2026-05-14栏目: 教程
