Skip to content

Dependency Injection Singleton Pattern 0.8 release

Thomas Cashman edited this page Aug 16, 2013 · 1 revision

This tutorial shows how mini2Dx uses the Singleton pattern for dependency injection. However mini2Dx plans to support Prototype dependency injection in the future.

Basic Dependency Injection

A BeanRepository provides access to singleton beans (java classes). In the example below, the developer has defined a Camera class which requires a Player instance to be autowired in.

public class Camera {
		@Autowired
		private Player player;

		...
}
public class Player {
		private int x;
		private int y;

		...
}

By registering each of these classes with the SingletonBeanRepository an instance of Player will be injected into the Camera instance. This will only happen once the close() method is called on the repository.

SingletonBeanRepository.open();
SingletonBeanRepository.registerBean(Camera.class);
SingletonBeanRepository.registerBean(Player.class);
SingletonBeanRepository.close();

Fetching an instance of these classes from the SingletonBeanRepository will always return the same instance.

Player player1 = SingletonBeanRepository.getBean(Player.class);
Player player2 = SingletonBeanRepository.getBean(Player.class);
//Player 1 will be the same instance as Player 2

Hot-swapping implementations

The benefit of using dependency injection is that by using interfaces, implementations can be hot-swapped. In the example below the developer has made an interface for input handling. The Player class required an implementation of InputHandler to be autowired in.

public interface InputHandler {
		public void handleButtonPress(int keycode);
}
public class Player {
		@Autowired
		private InputHandler inputHandler;

		private int x;
		private int y;

		...
}

The developer can now register a desktop-specific implementation of this interface in their desktop application.

public class DesktopInputHandler implements InputHandler {
		public void handleButtonPress(int keycode) {
				//Desktop specific code here
		}
}

Likewise, Android-specific version can be implementation inside their Android application.

public class AndroidInputHandler implements InputHandler {
		public void handleButtonPress(int keycode) {
				//Android specific code here
		}
}

Clone this wiki locally