反射的方式破解单例模式

上篇文章中前两种单例实现方式可以通过反射来进行破解

package com.zkn.newlearn.test.gof;

import static org.junit.Assert.*;

import java.lang.reflect.Constructor;

import org.junit.Test;

import com.zkn.newlearn.gof.singleton.SingletonTest01;
import com.zkn.newlearn.gof.singleton.SingletonTest02;
import com.zkn.newlearn.gof.singleton.SingletonTest05;

public class TestSingleton01 {	
	/**
	 * 破解单例
	 * @throws ClassNotFoundException 
	 * @throws NoSuchMethodException 
	 * @throws SecurityException 
	 */
	@Test
	public void testTest2() throws Exception {
		
		Class clazz = Class.forName("com.zkn.newlearn.gof.singleton.SingletonTest02"); 
		Constructor con = clazz.getDeclaredConstructor(null); //无参构造函数
		con.setAccessible(true);// 设置private权限修饰符为可见
		SingletonTest02 sin1 = (SingletonTest02) con.newInstance();
		SingletonTest02 sin2 = (SingletonTest02) con.newInstance();
		System.out.println(sin1 = sin2); //false
		System.out.println(sin1);
		System.out.println(sin2);
	}
	
}

猜你喜欢

转载自zknxx.iteye.com/blog/2301606
今日推荐