您的位置:首页 > 其它

单例模式---孤独的寂寞

2016-12-04 21:12 267 查看
声明:文章内容根据大牛博客的内容,自己理解后,给自己做的学习笔记,文末会附上大牛博客地址链接。有需要沟通交流的可加我QQ群:425120333
说真的,看懂设计模式了,和会用,在这之间还差了N行代码,每个设计模式都是前人经验的结晶,先去理解再去用(千万别在代码中强行使用)。
首先,就是单例模式,顾名思义,就是一个类在整个运行期间只会有一个实例,每次获取到的都是同一实例。实现单例模式的方式各种各样,
每种方式都有各自的特点,需要根据实际情况进行选择。


/**
* @author caiqibin
* @introduce:类被调用就创建(可能只是用到类中其他的静态方法),可能浪费空间
*
*/
public class Singleton {
private static Singleton singleton = new Singleton();

private Singleton() {

}

public static Singleton getSingleton() {
return singleton;
}
}

/**
* @author caiqibin
* @introduce:单线程下可行,多线程下不能保证单例
*
*/
class SingletonA {
private static SingletonA singleton;

private SingletonA() {

}

public static SingletonA getSingleton() {
if (singleton == null) {
singleton = new SingletonA();
}
return singleton;
}
}

/**
* @author caiqibin
* @introduce:多线程下也可行,但是加了同步,多了很多等待,浪费时间
*
*/
class SingletonB {
private static SingletonB singleton;

private SingletonB() {

}

public synchronized static SingletonB getSingleton() {
if (singleton == null) {
singleton = new SingletonB();
}
return singleton;
}
}

/**
* @author caiqibin
* @introduce:双重检测校验,一般来说都可以,而且不会有问题。
*                                    创建对象三步走:1分配内存空间,2初始化构造器,3将对象指向分配的内存地址(因为jvm的指令重排序
*                                    ,2、3的顺序无法保证)所以导致可能出现问题
*/
class SingletonC {
private static SingletonC singleton;

private SingletonC() {

}

public static SingletonC getSingleton() {
if (singleton == null) {
synchronized (SingletonC.class) {
if (singleton == null) {
singleton = new SingletonC();
}
}
}
return singleton;
}
}

/**
* @author caiqibin
* @introduce:一定不会有问题(要jdk1.5以上才支持volatile关键字)
*
*/
class SingletonD {
private static volatile SingletonD singleton;

private SingletonD() {

}

public static SingletonD getSingleton() {
if (singleton == null) {
synchronized (SingletonD.class) {
if (singleton == null) {
singleton = new SingletonD();
}
}
}
return singleton;
}
}

/**
* @author caiqibin
* @introduce:最好的实现方式,没有限制,不会浪费
*
*/
class SingletonBest {

private SingletonBest() {

}

public static SingletonBest getSingleton() {
return CreateSingletonBest.singleton;
}

private static class CreateSingletonBest {
private static SingletonBest singleton = new SingletonBest();
}

}


这里我总共列出了6中,最后这种是最优的,而且没限制。当然,实际情况下还有其他写单例的方法,水平有限,还知道其他的请给我留言学习下,谢谢了!
参考大牛博客链接:http://www.cnblogs.com/zuoxiaolong/p/pattern2.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: