Spring的模块化是很强的,各个功能模块都是独立的,我们可以选择的使用。这一章先从Spring的IoC开始。所谓IoC就是一个用XML来定义生成对象的模式,我们看看如果来使用的。
数据模型
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 { /* (非 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("美国人以车代步,有四肢退化的趋势"); } }
|
2、对以上对象采用工厂模式的用法如下
创建一个工厂类Factory,如下。这个工厂类里定义了两个字符串常量,所标识不同的人种。getHuman方法根据传入参数的字串,来判断要生成什么样的人种。
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("参数(人种)错误"); } }
|
[1] [2] [3] 下一页

【责编:John】