笔记:单例的几种方式

单例模式:

单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。

  • 1、单例类只能有一个实例。
  • 2、单例类必须自己创建自己的唯一实例。
  • 3、单例类必须给所有其他对象提供这一实例。

介绍

意图:
保证一个类仅有一个实例,并提供一个访问它的全局访问点。

主要解决:
一个全局使用的类频繁地创建与销毁。

何时使用:
当您想控制实例数目,节省系统资源的时候。

如何解决:
判断系统是否已经有这个单例,如果有则返回,如果没有则创建。

关键代码:
构造函数是私有的。

1、懒汉式,线程不安全

public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
  
    public static Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
}

2、懒汉式,线程安全

public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
    
    public static synchronized Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
}

3、饿汉式,线程安全

public class Singleton {  
    private static Singleton instance = new Singleton();  
    private Singleton (){}  
    public static Singleton getInstance() {  
    return instance;  
    }  
}

4、双检锁/双重校验锁(DCL,即 double-checked locking)

 /*
    DK 版本:JDK1.5 起
    是否 Lazy 初始化:是
    是否多线程安全:是
    */
    public class Singleton {  
        private volatile static Singleton singleton;  
    
    	private Singleton (){}  
    
    	public static Singleton getSingleton() {  
    		if (singleton == null) {  
    			synchronized (Singleton.class) {  
    				if (singleton == null) {  
    					singleton = new Singleton();  
    				}  
    			} 
    		}
    		return singleton;  
    	}  
    }

5、登记式/静态内部类

public class Singleton {
    private Singleton() {}
//静态内部类
	private static class SingletonHolder {
    	static Singleton instance = new Singleton();
	}
 
	//外部类方法访问内部类静态成员
	public static Singleton getInstance() {
   	 return SingletonHolder.instance;
	}
}

6/枚举

JDK 版本:JDK1.5 起
是否 Lazy 初始化:否
是否多线程安全:是

public enum Singleton {  
    INSTANCE;  
    public void whateverMethod() {  
    }  
}

7、 静态块初始化

public class StaticBlockSingleton {
	private static StaticBlockSingleton instance;

	private StaticBlockSingleton(){}

	//static block initialization for exception handling
	static{
   	 	try{
      	  instance = new StaticBlockSingleton();
    	}catch(Exception e){
       	 throw new RuntimeException("Exception occured in creating singleton instance");
   	 }
	}

	public static StaticBlockSingleton getInstance(){
   	 return instance;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值