单例模式的5种写法
•发布于   •作者 我喜欢吃肉  •548 次浏览  •来自 博客

第一种,懒汉式

//1.单例模式--懒汉式
 class Singleton1{
	 private static  Singleton1 instance=null;
	 private Singleton1(){}
	 
	 public static Singleton1 getInstance(){
		 if(instance==null){
			 instance=new Singleton1();
		 }
		 return instance;
	 }
	 
	 public void whateverMethod(){
		 //TODO
	 }
 }


第二种,饿汉式

//2.单例模式--饿汉式
class Singleton2{
	 private static Singleton2 instance=new Singleton2();
	 private Singleton2(){}
	 
	 public static Singleton2 getInstance(){
		 return instance;
	 }
	 
	 public void whateverMethod(){
		 //TODO
	 }
 }

第三种,枚举(java1.5之后)

//3.单例模式--枚举
enum Singleton3{
	 INSTANCE;
	 
	 public void whateverMethod(){
		 //TODO
	 }
}


第四种,双重检查锁

//4.单例模式--双重检查锁
 class Singleton4{
	 private static Singleton4 instance=null;
	 private Singleton4(){}
	 
	 public static Singleton4 getInstance(){
		 if(instance==null){
			 synchronized(Singleton4.class){
				 if(instance==null){
					 instance=new Singleton4();
				 }
			 }
		 }
		 return instance;
	 }
	 
	 public void whateverMethod(){
		 //TODO
	 }
 }


第五种,静态内部类

//5.单例模式--使用静态内部类
class Singleton5{
	private static class SingletonHolder{
		private static final Singleton5 INSTANCE=new Singleton5();
	}
	private Singleton5(){}
	
	public static Singleton5 getInstance(){
		return SingletonHolder.INSTANCE;
	}
	
	public void whateverMethod(){
		 //TODO
	 }
}





0 回复
回到顶部

©2017 Powered by 三十三行伪代码
皖ICP备17005175号-3