1.单例模式:java中的解释是:一个类有且仅有一个实例,并且自行实例化向整个系统提供;是一种比较常见的设计模式。
优点:1,单例模式会阻止其他对象实例化自己对象的副本,进而确保了只有一个实例对象,让所有的对象都访问唯一实例;
2,单例模式控制其实例化过程,所以类可以灵活更改其实例化过程。
缺点:如果是懒汉式,每次对象请求引用时都要检查是否存在类的实例,会增加一部分开销。开发过程中,因为是单例模式所以不能使用new来实例化对象,影响开发人员的效率。
2.单例模式常见的模式:
1.懒汉式
public class Singleton1{ private static Singleton1 instance = null; private Singleton1(){ } public static Singleton1 getInstance(){ if(instance == null){ instance = new Singleton1(); } return instance; } }
2.饿汉式
public class Singleton2{ private static Singleton2 instance = new Singleton2(); private Singleton2(){ } public static Singleton2 getInstance(){ return instance; } }
两种方式都是通过将构造方法设为private来避免类在外部被实例化,获取实例只能通过getInstance()方法,这样能保证实例唯一。其中懒汉模式,是线程不安全的,要实现线程安全可以把getInstance()方法改为 public static synchronized Singleton1 getInstance();饿汉模式是类创建的同时就创建了一个静态的对象来供系统使用,此后不会再改变,是线程安全的。懒汉模式优化:
因为前面有说懒汉模式是线程不安全的,多线程的情况下,会出问题,单纯的把getInstance()方法改为 public static synchronized Singleton1 getInstance();这个解决方案又太影响效率,所以有下面比较好一点的懒汉模式
双重锁:
public class Singleton3{ private static Singleton3 instance; private Singleton3(){ } public static Singleton3 getInstance(){ if(instance == null){synchronized (Singleton3.class) { if (instance == null) { instance = new Singleton3(); } } } return instance; } }这种懒汉模式,只有在实例为空的时候,即实例还未创建时,会进行同步,否则就直接返回,减少了很多无谓的线程等待。
还有一种模式,应该算是单例模式进化的完整版啦:
public class Singleton4{ private Singleton4(){ } public static Singleton4 getInstance(){
return SingletonInstance.instance; }private static class SingletonInstance{
static Singleton4 instance = new Singleton4();
} }
这种实现,和饿汉模式比较相近,但是因为是内部类实现的,所以避免了一访问Singleton4就创建实例对象,哪怕你没有用到该实例对象,造成内存浪费。