DI(Dependency Injection)的基本思考(case实践)

来源:互联网 发布:良辰好景知几何txt书包 编辑:程序博客网 时间:2024/06/07 12:49

最初的一步

让我们赶快试一试吧。登场人物如下。

  • 问候语类
    • 返回问候语的字符串。
  • 问候客户端类
    • 从问候类获得问候语(字符串)并输出到终端屏幕。
  • 问候语应用主类
    • 启动用的类。用来组织问候语类和问候语使用者类的组成方式。
Greeting.java

问侯语的Interface。

package examples.di;public interface Greeting {    String greet();}
GreetingImpl.java

问候语的实装。

package examples.di.impl;import examples.di.Greeting;public class GreetingImpl implements Greeting {    public String greet() {        return "Hello World!";    }}
GreetingClient.java

使用问候语的使用者客户端Interface。

package examples.di;public interface GreetingClient {    void execute();}
GreetingClientImpl.java

使用问候语的客户端的实装。不是直接使用这个GreetngImpl(实装),而是通过Greeting(Interface)来实现问候的机能。

package examples.di.impl;import examples.di.Greeting;import examples.di.GreetingClient;public class GreetingClientImpl implements GreetingClient {    private Greeting greeting;    public void setGreeting(Greeting greeting) {        this.greeting = greeting;    }    public void execute() {        System.out.println(greeting.greet());    }}

机能提供端和使用端的准备都完成了。下面我们就执行一下试试吧。

GreetingMain.java
package examples.di.main;import examples.di.Greeting;import examples.di.impl.GreetingClientImpl;import examples.di.impl.GreetingImpl;public class GreetingMain {    public static void main(String[] args) {        Greeting greeting = new GreetingImpl();        GreetingClientImpl greetingClient = new GreetingClientImpl();        greetingClient.setGreeting(greeting);        greetingClient.execute();    }}

实行结果如下。

Hello World!

象这样机能的使用者(GreetingClientImpl)经由Interface(Greeting)的中介来使用机能,具体的机能对象(既Interface的实装类)在实行的时候由第三者(在这里是GreetingMain)来提供的情况,就是DI的基本思考方法。



<script type="text/javascript"><!--
google_ad_client = "pub-5873492303276472";
/* 728x90, 创建于 08-7-29 */
google_ad_slot = "7502041044";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

<script type="text/javascript"><!--google_ad_client = "pub-5873492303276472";/* 728x15, 创建于 08-7-29 */google_ad_slot = "7630759450";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-5873492303276472";/* 728x90, 创建于 08-7-29 */google_ad_slot = "7502041044";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击