1分钟学会单例模式

来源:互联网 发布:php 订单发货系统 编辑:程序博客网 时间:2024/04/27 15:36

//下面就是一个单例模式的类, 在调用时, 只可能创建一个实例

package com.yenange.singleton;

public class Singleton {
    private static Singleton instance=null;
    public static synchronized Singleton getSingleton() {
        if (instance==null) {
            instance=new Singleton();
        }
        return instance;
    }
}

 

//步骤:

//1.创建一个静态的本类的实例, 并且=null;

//2.创建一个静态的、同步的,返回本类的方法。内容:如果前面的那个实例为null, 则创建一个新的对象。返回那个实例即可。

------------------------------------------------------------------

singleton:单个元素集合。

instance: 实例。

synchronized: 同步的。