首页 > 编程 > Java > 正文

java Signleton模式详解及示例代码

2019-11-26 13:44:45
字体:
来源:转载
供稿:网友

Singleton模式是创建模式。

这种模式只涉及一个类是负责创建自己的对象。

该类确保只有一个对象获得创建。

这个类提供了一种方法来访问它的唯一对象。

例如,当设计一个用户界面,我们只能有一个主应用程序的窗口。我们可以使用Singleton模式,以确保有是MainApplicationWindow对象的一个​​实例。

下面的代码将创建一个主窗口类。

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();  }}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表