使用工厂模式实现单例

最近一直在看设计模式和基本原则,下面分享一个使用工厂模式实现单例。因为工厂模式我们在日常的开发中比较常用。所以最近get了一下。

1.首先写一个自己需要的单例模式。根据自己的业务而定。

package com.singleton.cn;

public class Singleton {

	private Singleton() {
	}
	public void doSomething() {
		System.err.println("开始做事情了");
	}
	
}

2.编写工厂:

package com.singleton.cn;

import java.lang.reflect.Constructor;

public class SingletonFactory {
	private static Singleton singleton;
	static {
		try {
			//反射获取class
			Class<?> cl = Class.forName(Singleton.class.getName());
			//根据构造方法构造
			Constructor<?> declaredConstructor = cl.getDeclaredConstructor();
			//设置该单例是否允许被创建
			declaredConstructor.setAccessible(true);
			//获取实例
			singleton = (Singleton)declaredConstructor.newInstance();
		} catch (Exception e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
	}
	
	public static Singleton getSingleton() {
		return singleton;
	}
}

 3.测试:

package com.singleton.cn;

public class Test {
	public static void main(String[] args) {
		Singleton singleton = SingletonFactory.getSingleton();
		singleton.doSomething();
		System.err.println(singleton);
	}
}

 4.输出:

开始做事情了
com.singleton.cn.Singleton@7852e922

猜你喜欢

转载自blog.csdn.net/qq_37228713/article/details/82780518