Pattern: 单例模式及其序列化实现

本文介绍了单例模式的四种实现方法:最简单的单例模式实现、使用静态工厂方法、利用静态内部类以及序列化的单例模式。每种实现都有其特点和适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单例模式有很多种写法,推荐一篇比较好的文章

http://devbean.blog.51cto.com/448512/203501


读完上面的文章之后,你可以看看我这篇来自 Effective Java 的单例实现。


1. 最简单的单例模式实现

//Singleton with final field - page 10
public class Elvis {
	public static final Elvis INSTANCE = new Elvis();

	private Elvis() {
		// ...
	}

	// ... // Remainder omitted

	public static void main(String[] args) {
		System.out.println(Elvis.INSTANCE);
	}
}

2. 静态工厂方法实现单例模式

//Singleton with static factory
public class Elvis {
	private static final Elvis INSTANCE = new Elvis();

	private Elvis() {
		// ...
	}

	public static Elvis getInstance() {
		return INSTANCE;
	}

	// ... // Remainder omitted
	public static void main(String[] args) {
		System.out.println(Elvis.INSTANCE);
	}
}

这两种方式的实现差异性,下面截图给出解释




3. 静态内部类实现单例模式

/**
 * When the getInstance method is invoked for the first time, it reads
 * SingletonHolder.uniqueInstance for the first time, causing the
 * SingletonHolder class to get initialized.The beauty of this idiom is that the
 * getInstance method is not synchronized and performs only a field access, so
 * lazy initialization adds practically nothing to the cost of access. A moder
 * VM will synchronize field access only to initialize the class.Once the class
 * is initialized, the VM will patch the code so that subsequent access to the
 * field does not involve any testing or synchronization.
 * 
 * @author mark
 * 
 */
public class Singleton {

	// an inner class holder the uniqueInstance.
	private static class SingletonHolder {

		static final Singleton uniqueInstance = new Singleton();
	}

	private Singleton() {
		// Exists only to default instantiation.
	}

	public static Singleton getInstance() {

		return SingletonHolder.uniqueInstance;
	}

	// Other methods...
}


第三种实现的好处可以参见上面的英文注释,自己意会大师的教导吧!


4. 单例模式的序列化

/ Serialzable Singleton - Page 11

import java.io.*;

public class Elvis {
    public static final Elvis INSTANCE = new Elvis();

    private Elvis() {
        // ...
    }

    // ...  // Remainder omitted

    // readResolve method to preserve singleton property
    private Object readResolve() throws ObjectStreamException {
        /*
         * Return the one true Elvis and let the garbage collector
         * take care of the Elvis impersonator.
         */
        return INSTANCE;
    }

    public static void main(String[] args) {
        System.out.println(Elvis.INSTANCE);
    }
}

更多的解释可以继续阅读这本书,这里只是提示大家。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值