一、定义单例模式保证了程序中只有一个实例但是可以在全局中访问到。
二、优势1、由于只有一个实例,故可以减少内存开销2、可以避免对资源的多重占用,避免对同一资源进行多种操作3、设置了全局的资源访问,可以优化和共享全局资源访问
三、常用方式
public class Singleton {
private static Singleton instance=null;
public Singleton(){
}
public static Singleton getInstance(){
if (instance==null) {
instance=new Singleton();
}
return instance;
}
}
(2)
加锁方式
public
static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
(3)饿汉式
//定义变量存储创建好的实例
//并且创建对象 只一次 在类加载的时候
private static Singleton instance = new Singleton();
//私有化构造方法 防止外部创建对象
private Singleton() {
}
//提供一个类静态方法返回单例对象 可以全局访问
public static Singleton getInstance() {
//类加载机制保证了实例的创建 就不需要做判断 直接返回
return instance;
}
说明:饿汉单例模式线程安全。
——————————————————————————————————————————
缺点:在不同的编译环境下可能出现不同的问题
public class Singleton {
/**
* 私有的构造器
*/
private Singleton() {
}
/**
* 内部类实现单例模式
* 延迟加载,减少内存开销
*
*/
private static class SingletonHolder {
private static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
protected void method() {
System.out.println("sssss");
}
}