单例模式1

来源:互联网 发布:遥感数据销售 编辑:程序博客网 时间:2024/06/05 11:34

1 饿汉式:

/** * @author  * @version 0.1 * 单例模式:饿汉式 -- 创建时进行实例化 *         1 私有化构造方法; *         2 创建私有实例(static) *         3 创建公共类方法(static)方法输出单例 */public class Singleton5 {    //创建私有实例    private static Singleton5 singleton5 = new Singleton5();    //创建私有构造方法    private Singleton5(){    }    //公共方法    public static Singleton5 getSingleton5(){        return singleton5;    }}


2 懒汉式

/** * @author  * @version 0.1 * 单例模式:懒汉式 -- 需要输出单例时创建并输出单例,存在线程安全问题 *             1 私有化构造器 *             2 创建默认的私有属性,不实例化 *             3 公开的获取单例方法,在方法内进行实例化,在此存在线程安全问题 */public class Singleton6 {    //默认的私有属性    private static Singleton6 singleton6;    //私有化构造器    private Singleton6(){}    //公有的获取单例方法    public static Singleton6 getSingleton6(){        if(singleton6 == null){            singleton6 = new Singleton6();        }        return singleton6;    }}




原创粉丝点击