分类: Java
2010-03-26 15:13:20
package cn.com.chengang.spring; public interface Human { void eat(); void walk(); } package cn.com.chengang.spring; public class Chinese implements Human { /* (非 Javadoc) * @see cn.com.chengang.spring.Human#eat() */ public void eat() { System.out.println("中国人对吃很有一套"); } /* (非 Javadoc) * @see cn.com.chengang.spring.Human#walk() */ public void walk() { System.out.println("中国人行如飞"); } } package cn.com.chengang.spring; public class American implements Human { /* (非 Javadoc) * @see cn.com.chengang.spring.Human#eat() */ public void eat() { System.out.println("美国人主要以面包为主"); } /* (非 Javadoc) * @see cn.com.chengang.spring.Human#walk() */ public void walk() { System.out.println("美国人以车代步,有四肢退化的趋势"); } } |
package cn.com.chengang.spring; public class Factory { public final static String CHINESE = "Chinese"; public final static String AMERICAN = "American"; public Human getHuman(String ethnic) { if (ethnic.equals(CHINESE)) return new Chinese(); else if (ethnic.equals(AMERICAN)) return new American(); else throw new IllegalArgumentException("参数(人种)错误"); } } |
package cn.com.chengang.spring; public class ClientTest { public static void main(String[] args) { Human human = null; human = new Factory().getHuman(Factory.CHINESE); human.eat(); human.walk(); human = new Factory().getHuman(Factory.AMERICAN); human.eat(); human.walk(); } } |
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" ""> <beans> <bean id="Chinese" class="cn.com.chengang.spring.Chinese"/> <bean id="American" class="cn.com.chengang.spring.American"/> </beans> |
package cn.com.chengang.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class ClientTest { public final static String CHINESE = "Chinese"; public final static String AMERICAN = "American"; public static void main(String[] args) { // Human human = null; // human = new Factory().getHuman(Factory.CHINESE); // human.eat(); // human.walk(); // human = new Factory().getHuman(Factory.AMERICAN); // human.eat(); // human.walk(); ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml"); Human human = null; human = (Human) ctx.getBean(CHINESE); human.eat(); human.walk(); human = (Human) ctx.getBean(AMERICAN); human.eat(); human.walk(); } } |
<bean id="Chinese" class="cn.com.chengang.spring.Chinese"/> |
human = (Human) ctx.getBean(CHINESE); |
new FileSystemXmlApplicationContext("src/cn/com/chengang/spring/bean.xml"); |
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" ""> <beans> <bean id="Chinese" class="cn.com.chengang.spring.Chinese" singleton="true"> <property name="humenName"> <value>陈刚</value> </property> </bean> <bean id="American" class="cn.com.chengang.spring.American"/> </beans> |