依赖注入模式【其他模式】

@SuppressWarnings("boxing")
public class DependencyInjection {
	/**
	 * Dependency Injection Pattern【依赖注入模式】:保持软件组件之间的松散耦合【低类间耦合】
	 */
	@Test
	public void all() {
		final Injector injector = Guice.createInjector(new UserModule());
		final UserDao userDao = injector.getInstance(UserDao.class);
		final long id = 1L;
		final String name = "zxd";
		userDao.add(User.of(id, name));
		Optional<User> user = userDao.getById(1L);
		assertTrue(user.isPresent());
		assertEquals(name, user.get().getName());
		userDao.remove(id);

		user = userDao.getById(id);
		assertFalse(user.isPresent());
	}
}

@Value(staticConstructor = "of")
class User {
	private Long id;
	private String name;
}

interface UserDao {
	int add(User user);

	Optional<User> getById(Long id);

	int remove(Long id);
}

class DataStore {
	private final ConcurrentMap<Long, User> USERS = new ConcurrentHashMap<>();

	public User getById(Long id) {
		return USERS.get(id);
	}

	public void persist(User user) {
		USERS.put(user.getId(), user);
	}

	public void remove(Long id) {
		USERS.remove(id);
	}
}

class UserDaoImpl implements UserDao {
	/**
	 *	通过 Juice 的 @Inject 注解完成注入
	 */
	@Inject
	private DataStore dataStore;

	@Override
	public int add(User user) {
		dataStore.persist(user);
		return 1;
	}

	@Override
	public Optional<User> getById(Long id) {
		return Optional.ofNullable(dataStore.getById(id));
	}

	@Override
	public int remove(Long id) {
		dataStore.remove(id);
		return 1;
	}
}
class UserModule extends AbstractModule {
	@Override
	protected void configure() {
		// 配置绑定关系,用于创建实例和依赖注入
		bind(DataStore.class).toInstance(new DataStore());
		bind(UserDao.class).to(UserDaoImpl.class);
	}
}

posted on 2019-01-05 20:17  竺旭东  阅读(87)  评论(0编辑  收藏  举报

导航