依赖注入的模拟

一 依赖注入和控制反转(DI & IoC)
1 依赖注入的模拟
//客户端代码
public class Business implements IBeanAware {
	private IWriter writer;

	public Business() {

	}

	// type1 Constructor Injection
	public Business(IWriter writer) {
		this.writer = writer;
	}

	// type2 Interface Injection
	@Override
	public void injectBean(Object dependcy) {
		writer = (IWriter) dependcy;
	}

	// type3 Setter Injection
	public void setWriter(IWriter writer) {
		this.writer = writer;
	}

	public void save() {
		writer.write();
	}

	public static void main(String[] args) throws Exception {
		BeanFactory applicationContext = BeanFactory.getInstance();
		Business biz = (Business)applicationContext.getBean("business");
		biz.save();
	}
}


// 组件代码
interface IWriter {
	public void write();
}

class FileWriter implements IWriter {
	@Override
	public void write() {
		System.out.println("write into file.");
	}
}

class ConsoleWriter implements IWriter {
	@Override
	public void write() {
		System.out.println("write into console.");
	}
}


//模拟IoC容器,管理依赖注入
@SuppressWarnings("unchecked")
class BeanFactory {
	private static BeanFactory applicationContext;
	private Object bean;
	private Properties props;

	private BeanFactory() throws Exception {
		props = new Properties();
		props.load(new FileInputStream("bean.properties"));
	}

	public static BeanFactory getInstance() throws Exception {
		if (applicationContext == null)
			applicationContext = new BeanFactory();
		return applicationContext;
	}

	public Object getBean(String beanName) throws Exception {
		IWriter writer = (IWriter) Class.forName(props.getProperty("writer"))
				.newInstance();
		Class<Business> claz = (Class<Business>) Class.forName(props
				.getProperty(beanName));
		Constructor<Business> c = claz.getConstructor(IWriter.class);

		if (c.getParameterTypes().length != 0) {
			bean = c.newInstance(writer);
			System.out.println("type1 Constructor Injection");
		} else if (bean instanceof IBeanAware) {
			bean = claz.newInstance();
			IBeanAware aware = (IBeanAware)bean;
			aware.injectBean(writer);
			System.out.println("type2 Interface Injection");
		} else {
			bean = claz.newInstance();
			Method m = claz.getDeclaredMethod("setWriter", IWriter.class)
m.invoke(bean, writer);
			System.out.println("type3 Setter Injection");
		}
		return bean;
	}
}

interface IBeanAware {
	public void injectBean(Object dependcy);
}


bean.properties
business = org.powersoft.spring.demo.Business
writer = org.powersoft.spring.demo.FileWriter
#writer = org.powersoft.spring.demo.ConsoleWriter


你可能感兴趣的:(spring,C++,c,bean,IOC)