JAVA设计模式之单例模式

来源:互联网 发布:微信朋友圈 淘宝链接 编辑:程序博客网 时间:2024/06/07 09:44

在应用程序中,有些资源是全局共享的,整个应用程序只需要一个就够了,多了反而会产生冲突,例如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() {    }}


0 0
原创粉丝点击