比较常说的单例模式也就是懒汉模式和饿汉模式,今天写上其他三种实现的方法。(1使用static块创建2使用静态内置类3使用静态枚举)
单例模式,顾名思义也就是我只生成一个实例供给别人使用。
具体的看一下代码那就知道怎么写了
//单例模式(饿汉模式)
public class Singleton {
private Singleton(){}
private static Singleton singleton = new Singleton();
public static Singleton getInstace(){
return singleton;
}
}
//单例模式(懒汉模式)
public class Singleton1 {
private Singleton1(){}
private static Singleton1 singleton1;
public static Singleton1 getSingleton1(){
if(singleton1 == null){
synchronized (singleton1) {
if (singleton1 == null) {
singleton1 = new Singleton1();
}
}
}
return singleton1;
}
}
//单例模式(使用static块)
public class Singleton2 {
private Singleton2(){
}
private static Singleton2 singleton2;
static{
singleton2 = new Singleton2();
}
public static Singleton2 getSingleton2(){
return singleton2;
}
}
//单例模式(使用静态内置类)
public class Singletion3 {
private Singletion3(){};
public static class Singletion3A{
private static Singletion3 singletion3 = new Singletion3();
public static Singletion3 getSingletion3(){
return singletion3;
}
}
}
//单例模式(使用静态枚举)
public class Singletion4 {
private Singletion4(){};
public static enum Singletion4A{
Sim;
private Singletion4 singletion4 = new Singletion4();
public Singletion4 getInstace(){
return singletion4;
}
}
}