软件151  王帅

1三个类,Human(人类)是接口,Chinese(中国人)是一个子类,American(美国人)是另外一个子类。

代码如下:

package cn.com.chengang.spring;
public interface Human {
void eat();
void walk();
}
package cn.com.chengang.spring;
public class Chinese implements Human {
public void eat() {
System.out.println("中国人对吃很有一套");
}
public void walk() {
System.out.println("中国人行如飞");
}
}
package cn.com.chengang.spring;
public class American implements Human {
public void eat() {
System.out.println("美国人主要以面包为主");
}
public void walk() {
System.out.println("美国人以车代步,有四肢退化的趋势");
}
}

2、创建一个工厂类Factory

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("参数(人种)错误");
}
}

3、采用SpringIoC的用法如下:在项目根目录下创建一个bean.xml文件

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="Chinese" class="cn.com.chengang.spring.Chinese"/>
<bean id="American" class="cn.com.chengang.spring.American"/>
</beans>

 

4、ClientTest测试程序

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) {
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();
}
}

 

 

posted on 2017-06-27 14:38  世.外.人  阅读(338)  评论(0编辑  收藏  举报