-
有一些对象我们只需要一个
例如
线程池
数据库连接
缓存cache
对话框
注册表
日志对象
打印机、显卡等设备驱动程序的对象
-
单例模式
确保一个类只有一个实例, 并提供一个全局访问点
-
有的情况下是直接初始化好这个实例, 有的情况下是延迟初始化这个实例, 这取决于这个对象是否是资源敏感型的
-
单例模式的类也可以是一般的类, 含有自己的数据和方法。 把一个一般的类变成单例很简单, 见下面的几种方法
-
单例模式的几种实现
(1) 饿汉模式直接创建实例
public class Singleton { private static Singleton uniqueInstance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return uniqueInstance; } // other useful methods here public String getDescription() { return "I'm a statically initialized Singleton!"; } }
(2) 不顾一切使用synchronized(一般不要用)
public class Singleton { private static Singleton uniqueInstance; // other useful instance variables here private Singleton() { } public static synchronized Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } // other useful methods here public String getDescription() { return "I'm a thread safe Singleton!"; } }
(3) 双锁单例模式(在JDK1.5以后才可以用这种实现, 并且实现略微有点复杂)
public class Singleton { private volatile static Singleton uniqueInstance; private Singleton() { } public static Singleton getInstance() { if (uniqueInstance == null) { synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } } } return uniqueInstance; } }
(4) 使用静态内部类Holder(懒汉模式下__最推荐__这种实现)
public class Singleton { private static class SingletonHolder { private static Singleton singletonInstance = new Singleton(); } // other useful instance variables here private Singleton() { } public static synchronized Singleton getInstance() { return SingletonHolder.singletonInstance; } // other useful methods here public String getDescription() { return "I'm a inner class holder Singleton!"; } }
-
如果有两个或以上的类加载器, 那么它们如果都加载了使用单例模式的类, 将会创建不同的实例, 所以这种情况下应该自行使用一个类加载器
-
轻易不要使用子类继承单例类的形式。 因为单例类的构造器是私有的, 而子类要继承的话又必须要让构造器不能是私有的: 如果构造器不是私有的, 那么说父类是一个单例的说法也就不成立了
所以, 不要使用这种形式。 如果想让子类是单例, 直接把它变成单例就好, 反正实现也不复杂
-
Java中实现单例模式的三件套
私有构造器
一个静态变量
一个静态方法
chapter05_独一无二的对象——单例模式
猜你喜欢
转载自blog.csdn.net/captxb/article/details/87899870
今日推荐
周排行