zeromsi/Design-Patterns

Breach of Singleton pattern by instantiating with reflection API

Closed this issue · 1 comments

With Reflection API, singleton pattern can be breached. The code snippet is as follows.

      		Car objectOne = Car.getInstance();
		Car objectTwo = Car.getInstance();
		System.out.println(objectOne);
		System.out.println(objectTwo);
		
		// Breaching with reflection API
		Class clazz  = Class.forName("com.msi.creationaldesignpattern.singleton.Car");
		Constructor<Car> ctor = clazz.getDeclaredConstructor();
		ctor.setAccessible(true);
		Car objectThree = ctor.newInstance();
		System.out.println(objectThree);

		

Output

com.msi.creationaldesignpattern.singleton.Car@15db9742
com.msi.creationaldesignpattern.singleton.Car@15db9742
com.msi.creationaldesignpattern.singleton.Car@6d06d69c

The fix is throwing an exception within constructor. This will restrict user from creating a new instance.

The following commit contains the solution.

c1c8697