05.创建型————单例模式

单例模式分为两种,懒汉式和饿汉式。区别在于创建实例的时机。饿汉式在该类加载时创建实例,懒汉式则在需要获取时才进行创建。

package Create.f.Singleton;

public class Singleton {
	private Singleton(){
		
	}
	protected static Singleton getInstance(){
		System.out.println("获取Singleton单例对象");
		return instance;
	}
	private static Singleton instance = new Singleton(); //饿汉式  注意此时线程安全
}

  

package Create.f.Singleton;

//懒汉式
public class Singleton2 {
	private static Singleton2 instance = null;
	private Singleton2(){
		
	}
	protected static synchronized Singleton2 getInstance(){
		if(instance == null){
			System.out.println("初始化Singleton2单例对象");
			instance = new Singleton2();
		}
		return instance;
	}
}

  

package Create.f.Singleton;

public class Client {
	public static void main(String[] args) {
		Singleton singleton = Singleton.getInstance();
		Singleton s = Singleton.getInstance();
		System.out.println("是否同个对象:" + (singleton == s));
		
		
		Singleton2 s2 = Singleton2.getInstance();
		Singleton2 s3 = Singleton2.getInstance();
		Singleton2 s4 = Singleton2.getInstance();
		
		System.out.println("是否同个对象:" + (s2 == s3 && s3 == s4));
		
	}
}

  

 

优点:客户调用类的时候,只能调用一个公共的接口,提供一个共享的概念

缺点:在多个虚拟机下运行时,要想知道具体哪个虚拟机运行着哪些单例是很困难的,而且可能存在着多线程安全和效率问题,此外还很难实现序列化

posted @ 2016-01-02 21:32  ciade  阅读(229)  评论(0编辑  收藏  举报