WebWork中实现IoC(5) (完)

来源:互联网 发布:怎么学人工智能编程 编辑:程序博客网 时间:2024/06/03 18:54
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

5、例子

作为小结,看一个例子。假设要创建一个称体重的刻度器;这些刻度器要在地球、金星和火星上出售。这里有个问题:各个星球上的重力是不同的。这就必须灵活的处理这个问题,以便保证他们能够获得正确的体重。下面是实现IoC的组成部分:

l         components.xmlIoC配置文件)

l         Scale.java(所有组件的接口)

l         ScaleAware.java enabler接口)

l         MarsScaleImpl.java(组件)

l         VenusScaleImpl.java(组件)

l         EarthScaleImpl.java(组件)

l         ScaleAction.javaAction类)

下面是components.xmlMarsScaleImpl注册的例子:

<components>
    <component>
        <scope>application</scope>
        <class>com.flyingbuttress.scale.MarsScaleImpl</class>
        <enabler>com.flyingbuttress.scale.ScaleAware</enabler>
    </component>
</components>

下面是Action类的代码,实现了ScaleAware接口:

public class ScaleAction implements Action, ScaleAware
{
       private Scale scale;
 
       public void setScale(Scale scale)
       {
              this.scale = scale;
       }
       public String execute() throws Exception
       {
              System.out.println("The weight of you is:" + scale.getWeight());
              return SUCCESS;
       }
}

现在,对于在火星上出售的刻度器,只要在components.xml中将<class />设置为MarsScaleImpl;对于在地球上出售的刻度器,只要将<class />设置为EarthScaleImpl;对于在金星上出售的刻度器,只要将<class />设置为VenusScaleImpl

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击