单例模式(饿汉式、懒汉式)

  • Post author:
  • Post category:其他




单例模式



1、单例模式简介

所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法。



2、单例模式实现——饿汉式

public class Singleton{

	private static final Singleton instance = new Singleton();

	// 私有化类的构造器,使它在类的外部不能被实例化
	private public Singleton(){
	}
	//静态方法返回实例
	public static Singleton getStingleton(){
		return instance;
	}
	
}

这种方式是线程安全的



3、单例模式——懒汉式



3.1、 线程不安全的懒汉式

public class Singleton{
	private stataic Singleton instance;
	// 私有化类的构造器,使它在类的外部不能被实例化
	private public Singleton(){
	}
	//静态方法返回实例
	public static Singleton getStingleton(){
		if(instance == null){
			instance = new Singleton();
		}
		return instance;
	}
	
}



3.2、线程安全的懒汉式

public class Singleton{

	private static Singleton instance;

	// 私有化类的构造器,使它在类的外部不能被实例化
	private public Singleton(){
	}
	//静态方法返回实例、实现同步
	public static synchronized Singleton getStingleton(){
		if(instance == null){
			instance = new Singleton();
		}
		return instance;
	}
	
}



版权声明:本文为weixin_44076559原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。