单例类Singleton

来源:互联网 发布:hadoop java c 编辑:程序博客网 时间:2024/06/05 16:19

单例类的使用
1.为什么使用单例类
因为如果大部分时候类的构造器定义成public权限,允许自由创建该类的对象, 但在某些时候自由创建对象并没有任何意义,还会造成系统性能下降。因此需要创建一种只能有一个实例的类——单例类。

class Singleton {    private static Singleton instance;    public static Singleton getInstance() {        if (instance == null)            instance = new Singleton();        return instance;    }}public class singletonDemo {    public static void main(String[] args) {    Singleton s1 = Singleton.getInstance();    Singleton s2 = Singleton.getInstance();    System.out.println(s1==s2);    //结果true    }}
0 0