猫头鹰的眼睛

导航

依赖注入之接口注入

书本上说:这种接口注入的方式需要调用者必须实现一个指定的接口,这种方式使用比较少,一般不推荐使用

1、项目截图

2、打印机接口类

package com.example.demo.printer;

/**
 * Created by Admin on 2018/5/8.
 */
public interface Printer {
    void init();

    void print(String txt);
}

3、彩色打印机类

package com.example.demo.printer;

public class ColorPrinter implements Printer {
    @Override
    public void init() {
        System.out.println("启动彩色打印机!");
    }

    @Override
    public void print(String txt) {
        System.out.println("打印彩色文字:".concat(txt));
    }
}

4、黑白打印机类

package com.example.demo.printer;

public class GrayPrinter implements Printer{

    @Override
    public void init() {
        System.out.println("启动打印机");
    }

    @Override
    public void print(String txt) {
        System.out.println("打印黑白文字:".concat(txt));
    }
}

5、电脑类

package com.example.demo.printer;

/**
 * Created by Admin on 2018/5/8.
 */
public class Computer implements Computeable{

    Printer p;
    public Printer getP() {
        return p;
    }

    public void setP(Printer p) {
        this.p = p;
    }

    @Override
    public void inject(Printer p) {
        this.p = p;
    }
}

6、电脑实现的接口

package com.example.demo.printer;

public interface Computeable {
    void inject (Printer p);
}

7、测试类

package com.example.demo.printer;

public class TestComputer {
    public static void main(String[] args) {
        Printer p = (Printer) GetBeans.getBean("printer");
        Computer pcl = new Computer();
        pcl.inject(p);

        //实现不用new关键字创建打印机实例
        pcl.getP().print("打印测试页...");
    }
}

8、配置文件

printer = com.example.demo.printer.ColorPrinter

9、效果:

 

posted on 2018-05-08 10:51  猫头鹰咖啡师  阅读(10815)  评论(0编辑  收藏  举报