单例模式
1. 双重校验实现单例
2. 使用静态内部类实现单例
3. 序列化反序列化实现单例
4. 使用static代码块实现单例
5. 使用enum枚举数据类型实现单例
public class Instance {
private volatile static Instance instance;
private Instance(){
}
public static Instance getInstance(){
if(instance == null){
synchronized (Instance.class) {
if(instance == null){
instance = new Instance();
}
}
}
return instance;
}
}
public class StaticInstance {
private static class MyStaticInstance{
private static StaticInstance staticInstance = new StaticInstance();
}
private StaticInstance(){
}
public static StaticInstance getInstance(){
return MyStaticInstance.staticInstance;
}
}
public class StaticCodeInstance {
private static StaticCodeInstance staticCodeInstance = null;
public StaticCodeInstance(){
}
static{
staticCodeInstance = new StaticCodeInstance();
}
public static StaticCodeInstance getStaticCodeInstance(){
return staticCodeInstance;
}
}
public class SerizalibleInstance implements Serializable{
private static final long serialVersionUID = 888L;
private static class MySerizelibleInstance{
private static SerizalibleInstance serizalibleInstance = new SerizalibleInstance();
}
private SerizalibleInstance(){
}
public static SerizalibleInstance getSerizalibleInstance(){
return MySerizelibleInstance.serizalibleInstance;
}
protected SerizalibleInstance ReadResolve(){
System.out.println("did Resolve !!!");
return MySerizelibleInstance.serizalibleInstance;
}
}
public class StaticEnumInstance {
public enum MyStaticEnumInstance{
mythread;
private Thread thread2;
private MyStaticEnumInstance(){
thread2 = new Thread();
}
public Thread getThread(){
return thread2;
}
}
public static Thread getMYThread(){
return MyStaticEnumInstance.mythread.getThread();
}
}