JAVA设计模式之单例模式

在应用程序中,有些资源是全局共享的,整个应用程序只需要一个就够了,多了反而会产生冲突,例如Windows系统中的回收站。于是,就有了单例模式,制造一个全局共享且唯一的对象,供整个应用程序使用。


单例模式分两种,懒汉模式和饿汉模式。


所谓懒汉模式,也是线程安全的,当有需要的时候,再去创建一个对象。

public class PictureLoader {
    
    private static PictureLoader pictureLoader = null;
    
    public static PictureLoader getPictureLoader(Context context) {
        if (pictureLoader == null) {
            synchronized (PictureLoader.class) {
                if (pictureLoader == null) pictureLoader = new PictureLoader(context);
            }
        }
        return pictureLoader;
    }
    private PictureLoader(Context context) {
    }
}
这样,全局就只有一个PictureLoader类的对象了。注意,类的构造方法要设置为private,这样就无法其他的类中创建该类的对象了。类的get方法要设置为public static公有静态方法。不然,其他的类就永远无法获取到该类的对象了。类的对象也要设置为static,否则无法在get方法中使用。


所谓饿汉模式,就是在一开始便建立一个对象, 不管有没有需要,我都先建好了,有需要的,拿来用就是,这样,就不存在线程安全的问题。

public class PictureLoader {
    
    private static PictureLoader pictureLoader = new PictureLoader();
    
    public static PictureLoader getPictureLoader() {
        return pictureLoader;
    }
    private PictureLoader() {
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值