Java设计模式之——单例模式

来源:互联网 发布:中国历史教科书知乎 编辑:程序博客网 时间:2024/06/06 06:59
单例设计模式
       所谓单例设计模式简单说就是无论程序如何运行,采用单例设计模式的类(Singleton类)永远只会有一个实例化对象产生。具体实现步骤如下:
      (1) 将采用单例设计模式的类的构造方法私有化(采用private修饰)。
      (2) 在其内部产生该类的实例化对象,并将其封装成private static类型。
      (3) 定义一个静态方法返回该类的实例。

         四种实现方法示例代码如下:

实现方式一:

/** * 单例模式的实现1:饿汉式,线程安全,但是效率低下 */public class SingletonTest01 {//创建私有实例变量private static SingletonTest01 instance = new SingletonTest01();//构造方法私有化private SingletonTest01(){}//声明静态公有的获取实例变量的方法public static SingletonTest01 getInstance(){return instance;}}

实现方式二:

/** * 单例模式的实现2:饱汉式,非线程安全 */public class SingletonTest02 {//声明私有实例变量,先不要实例化private static SingletonTest02 instance;//构造方法私有化private SingletonTest02(){}//获取实例变量的公有静态方法public static SingletonTest02 getInstance(){if(instance==null) instance = new SingletonTest02();return instance;}}

实现方式二:

/** * 单例模式实现3:线程安全,但是效率很低 */public class SingletonTest03 {//声明私有实例变量,先不要实例化private static SingletonTest03 instance;//构造方法私有化private SingletonTest03(){}//获取实例变量的公有静态方法public static synchronized  SingletonTest03 getInstance(){if(instance==null) instance = new SingletonTest03();return instance;}}

实现方式四:

/** * 单例模式的实现4:线程安全,效率高 */public class SingletonTest04 {//声明私有实例变量,先不要实例化private static SingletonTest04 instance;//构造方法私有化private SingletonTest04(){}//获取实例变量的公有静态方法public static   SingletonTest04 getInstance(){if(instance==null) {synchronized (SingletonTest04.class) {instance = new SingletonTest04();}}return instance;}}