单例模式

来源:互联网 发布:物流标签打印软件 编辑:程序博客网 时间:2024/05/22 08:19

单例模式:确保某一个类有且只有一个实例,而且自行实例化并向整个系统提供这个实例。

 

代码实现:

懒汉式单例:

package com.huey.demo.singleton.lazy;public class Singleton {private static Singleton singleton = null;/*** 私有的构造方法 */private Singleton() {}/*** 获得单例的方法,线程安全的 */public synchronized static Singleton getInstance() {if (singleton == null) {singleton = new Singleton();}return singleton;}}

测试代码:

package com.huey.demo.singleton;import com.huey.demo.singleton.lazy.Singleton;public class MainApp {public static void main(String[] args) {Singleton singleton1 = Singleton.getInstance();Singleton singleton2 = Singleton.getInstance();if (singleton1 == singleton2) {System.out.println("They are the same object.");} else {System.out.println("They are different objects.");}}}

结果输出:

They are the same object.

饿汉式单例:

package com.huey.demo.singleton.hungry;public class Singleton {/*** 在加载类之前初始化实例 */private static Singleton singleton = new Singleton();private Singleton() {}public static Singleton getInstance() {return singleton;}}

测试代码:

package com.huey.demo.singleton;import com.huey.demo.singleton.hungry.Singleton;public class MainApp {public static void main(String[] args) {Singleton singleton1 = Singleton.getInstance();Singleton singleton2 = Singleton.getInstance();if (singleton1 == singleton2) {System.out.println("They are the same object.");} else {System.out.println("They are different objects.");}}}

结果输出:

They are the same object.


两种方式的比较:

懒汉式:优点,不会产生内存浪费,因为共享实例对象开始没有被初始化,而是在获得对象的方法中动态生成实例的;缺点,在获取共享对象的方法上,使用syschronized线程同步,执行效率有所降低。

饿汉式:优点,由于没有syschronized线程同步,执行效率高;缺点,会产生内存浪费,因为在加载Singleton类时就已经初始化共享对象实例。