单例模式的实现
package singleton;
/**
* 饿汉式
* @author lenovo
*
*/
public final class Singleton {
private byte data[] =new byte[1024];
private static Singleton s = new Singleton();
private Singleton(){
}
public static Singleton gets() {
return s;
}
}
package singleton;
/**
* 懒汉式
* 多线程环境下无法保证单例的唯一性
* @author lenovo
*
*/
public final class LazySingleton {
private byte[] data= new byte[1024];
private static LazySingleton s =null;
private LazySingleton() {
}
public static LazySingleton gets() {
if(null==s) {
s= new LazySingleton();
}
return s;
}
}
package singleton;
/**
* 懒汉式加同步方法
* @author lenovo
*
*/
public class Singleton3 {
private byte[] data= new byte[1024];
private static Singleton3 s =null;
private Singleton3() {
}
public static synchronized Singleton3 gets() {
if(null==s) {
s= new Singleton3();
}
return s;
}
}
package singleton;
/**
* double-check方法
* 首次初始化时加锁
* 可能会发生初始化异常
* @author lenovo
*
*/
public class Singleton4 {
private byte[] data= new byte[1024];
private static Singleton4 s =null;
private Singleton4() {
}
public static Singleton4 gets() {
if(null==s) {
synchronized(Singleton4.class) {
if(null==s)
s= new Singleton4();
}
}
return s;
}
}
package singleton;
public class Singleton5 {
private byte[] data= new byte[1024];
private static volatile Singleton5 s =null;
private Singleton5() {
}
public static Singleton5 gets() {
if(null==s) {
synchronized(Singleton5.class) {
if(null==s)
s= new Singleton5();
}
}
return s;
}
}
package singleton;
/**
* holder
* 借助类加载的特点
* @author lenovo
*
*/
public class Singleton6 {
private byte[] data= new byte[1024];
private Singleton6() {
}
/**
* 在静态内部类中进行直接初始化
* @author lenovo
*
*/
private static class Holder{
private static volatile Singleton6 s =new Singleton6();
}
public static Singleton6 gets() {
return Holder.s;
}
}
1511

被折叠的 条评论
为什么被折叠?



