单例模式是指一个类在一个系统内部只有一个实例。
单例模式首先要考虑到如何进行初始化,这就要考虑构造函数了。下面是转载的一段。
通常构造函数是public的, 今天无意间写了一个default的构造函数, 在另外一个包里面使用的时候居然发现The constructor is not visible,于是有了兴趣, 试验发现private, protected都是not visible.回去翻书《Thinking in java》关于构造函数那一节也没有讲。
写了几个例子,发现构造函数也遵循普通函数的访问机制, 即:
public:所有的类都可以使用;
protected: 本包以及子类可以使用;
default:本包可以使用;
private:仅本类可以使用。
所以:
如果构造函数是private的,则不可被继承;也阻止了本类被继承(如果只有这一个构造函数的话).
转载请注明来自:http://blog.csdn.net/sunxing007
(1)第一种方式比较简单,直接通过静态变量实现,存在什么问题呢?
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16<span style="font-size:18px;">package com.ss.algorithm.singleton; /** * @author gongxw */ public class Singleton1 { /* * 空间换时间 * 这个对象不管你用不用都会存在在那里,如果是个大对象又不用,此种方法不可取 */ private static Singleton1 singleton = new Singleton1(); private Singleton1() {} public static Singleton1 getInstance() { return singleton; } } </span>
(2)通过在方法上加同步锁解决加载初始化的问题,同样也存在问题?
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22<span style="font-size:18px;">package com.ss.algorithm.singleton; /** * @author gongxw */ public class Singleton2 { private static Singleton2 singleton2 = null; /** * 私有默认构造函数 */ private Singleton2() {} /** * 每次进入这个方法都会加同步锁 * @return Singleton2 */ public static synchronized Singleton2 getInstance() { if (singleton2 == null) { singleton2 = new Singleton2(); } return singleton2; } } </span>
(3)double check,使用volatile变量,还是存在问题?《java并发编程实战》中不推荐这种。
复制代码
(4)使用类级内部类,相当于外部类的一个static变量,它的对象与外部类对象不存在依赖关系。可以通过外部类方法直接进行访问。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26<span style="font-size:18px;">package com.ss.algorithm.singleton; /** * @author gongxw */ public class Singleton3 { //编译器不会对下面的语句优化? 保持可见性? private volatile static Singleton3 singleton3 = null; private Singleton3() {} /** * 每次进入这个方法都会加同步锁 * double check * @return singleton3 */ public static Singleton3 getInstance() { if (singleton3 == null) { synchronized(Singleton3.class) { if (singleton3 == null) { singleton3 = new Singleton3(); } } } return singleton3; } } </span>
复制代码
1
2
3
4
5
6package com.ss.algorithm.singleton; /** * @author gongxw */ public class Singleton4 { private Singleton4() {}
复制代码
1
2
复制代码
1
2
3
4
5
6
7
8
9
10<span style="white-space:pre"> </span>/** * 类级内部类,不使用此内部类时,不会初始化,实现延迟加载和线程安全 */ private static class Singleton4Holder { private static Singleton4 singleton4 = new Singleton4(); } public static Singleton4 getInstance() { return Singleton4Holder.singleton4; } }
最后
以上就是谦让衬衫最近收集整理的关于设计模式之单例模式(创建型)的全部内容,更多相关设计模式之单例模式(创建型)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复