单例模式(Singleton pattern)

来源:互联网 发布:最近火的网络用语 编辑:程序博客网 时间:2024/05/21 22:22

定义:单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为。

结构图:

public class Singleton {public static Singleton s;public static Singleton GetInstance(){if (s == null) {s = new Singleton();}return s;}}public class Client {public static void main(String[] args) {Singleton s1 = new Singleton();Singleton s2 = new Singleton();if (s1 == s2) {System.out.println("same");}else {System.out.println("not the same");}}}

0 0
原创粉丝点击