package wangdi;
/**
* 懒汉式 线程不安全
* @author 王迪
*
*/
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null){
instance= new Singleton();
}
return instance;
}
}
/**
* 懒汉式 线程安全 效率很低
* @author 王迪
*
*/
class Singleton1 {
private static Singleton1 instance;
private Singleton1(){}
public static synchronized Singleton1 getInstance(){
if(instance==null){
instance= new Singleton1();
}
return instance;
}
}
/**
* 饿汉式 执行效率会提高 但容易产生垃圾
* @author 王迪
*
*/
class Singleton2 {
private static Singleton2 instance=new Singleton2();
private Singleton2(){}
public static Singleton2 getInstance(){
return instance;
}
}
/**
* 双检索/双重检验锁 可以做特殊需求
* @author 王迪
*
*/
class Singleton3 {
private volatile static Singleton3 instance;
private Singleton3(){}
public static Singleton3 getInstance(){
if(instance==null){
synchronized(Singleton3.class){
if(instance==null){
instance= new Singleton3();
}
}
}
return instance;
}
}
/**
* 登记式/静态内部类
* @author 王迪
*
*/
class Singleton4{
private static class SingletonHolder{
private static final Singleton4 INSTANCE= new Singleton4();
}
private Singleton4(){}
public static final Singleton4 getInstance(){
return SingletonHolder.INSTANCE;
}
}
/**
* 枚举型
* @author 王迪
*
*/
enum Singleton5{
INSTANCE;
public void whateverMethod(){
}
}
/**
* 懒汉式 线程不安全
* @author 王迪
*
*/
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null){
instance= new Singleton();
}
return instance;
}
}
/**
* 懒汉式 线程安全 效率很低
* @author 王迪
*
*/
class Singleton1 {
private static Singleton1 instance;
private Singleton1(){}
public static synchronized Singleton1 getInstance(){
if(instance==null){
instance= new Singleton1();
}
return instance;
}
}
/**
* 饿汉式 执行效率会提高 但容易产生垃圾
* @author 王迪
*
*/
class Singleton2 {
private static Singleton2 instance=new Singleton2();
private Singleton2(){}
public static Singleton2 getInstance(){
return instance;
}
}
/**
* 双检索/双重检验锁 可以做特殊需求
* @author 王迪
*
*/
class Singleton3 {
private volatile static Singleton3 instance;
private Singleton3(){}
public static Singleton3 getInstance(){
if(instance==null){
synchronized(Singleton3.class){
if(instance==null){
instance= new Singleton3();
}
}
}
return instance;
}
}
/**
* 登记式/静态内部类
* @author 王迪
*
*/
class Singleton4{
private static class SingletonHolder{
private static final Singleton4 INSTANCE= new Singleton4();
}
private Singleton4(){}
public static final Singleton4 getInstance(){
return SingletonHolder.INSTANCE;
}
}
/**
* 枚举型
* @author 王迪
*
*/
enum Singleton5{
INSTANCE;
public void whateverMethod(){
}
}