单例模式

来源:互联网 发布:stc89c51单片机烧录 编辑:程序博客网 时间:2024/06/05 21:51
/** * 懒汉式 */public class Singleton {    private static Singleton instance;    /**     * 1.构造方法私有化     */    private Singleton(){        System.out.println("创建对象");    }    /**     * 根据对象是否为空进行创建     */    public static synchronized Singleton getInstance(){        if(instance==null){            instance = new Singleton();        }        return instance;     }}
/** * 饿汉式 */public class Singleton {    private static Singleton instance = new Singleton();    /**     * 1.构造方法私有化     */    private Singleton(){        System.out.println("创建对象");    }    public static Singleton getInstance(){        return instance;     }}

这里写图片描述

0 0
原创粉丝点击