当前位置: 移动技术网 > IT编程>开发语言>Java > java Signleton模式详解及示例代码

java Signleton模式详解及示例代码

2019年07月22日  | 移动技术网IT编程  | 我要评论
singleton模式是创建模式。 这种模式只涉及一个类是负责创建自己的对象。 该类确保只有一个对象获得创建。 这个类提供了一种方法来访问它的唯一对象。 例如,当设

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

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网