Java中单例模式中的饿汉模式和懒汉模式

java的单例模式

java中面向对象中的单例模式是有套路的:

1.将所构造的函数私有化

2.在成员位置自己创建一个对象

3.对外构造一个方法

一、 第一种饿汉模式

下面展示一些 内联代码片

//饿汉模式
public class SingleInstance {
	//在成员位置自己创建一个对象
	private static final SingleInstance singleInstance = new SingleInstance();

	// 构造函数私有化
	private SingleInstance() {
		super();
		// TODO Auto-generated constructor stub
	}

	// 对外构造一个方法
	public static SingleInstance getSingleInstance() {
		return singleInstance;
	}

二、第二种懒汉模式

下面展示一些 内联代码片

public class SingleInstance {
	//在成员位置自己创建一个对象
	private static  SingleInstance singleinstance = null;

	// 构造方法私有化
	private SingleInstance() {
		super();

	}

	// 对外提供一个方法让别人来调用这个方法
	public static synchronized SingleInstance getSingleinstance() {
		if (singleinstance == null) {
			singleinstance = new SingleInstance();
			System.out.println("singleinstance == null");
		}
		return singleinstance;
	}

猜你喜欢

转载自blog.csdn.net/fdbshsshg/article/details/112794893