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

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

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);
    }
}

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




©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页