《Java编程思想》(笔记9)-- 接口

是决定花一段连续的时间把《Java编程思想》看一遍,看书怎么能不做笔记呢,明明知道自己有些地方看完肯定会忘掉的,所以想把每章的笔记重点放在博客上,与大家共享!

第九章 接口

1.适配接口

接口最吸引人的原因之一就是允许同一个接口具有多个不同的具体实现。
在简单的情况中,它的体现形式通常是一个接受接口类型的方法,而该接口的实现和向该方法传递的对象则取决于方法的使用者。
“你可以用任何你想要的对象来调用我的方法,只要你的对象遵循我的接口。”

2.接口中的域

放入接口中的任何域自动是static和final,所以接口就成为一种很便携的用来创建常量组的工具。

3.接口与工厂

工厂设计模式在工厂对象上调用创建方法,而该工厂对象将生产接口的某个实现的对象。通过这种方式,我们可以透明地将某个实现替换成另一个实现。

interface Service{
    void method1();
    void method2();
}
interface ServiceFactory{
    Service getService();
}
class Implementation1 implements Service{

    Implementation1(){}
    @Override
    public void method1() {
        System.out.println("Implementation1 method1");
    }

    @Override
    public void method2() {
        System.out.println("Implementation1 method2");
    }
}
class Implementation1Factory implements ServiceFactory{

    @Override
    public Service getService() {
        return new Implementation1();
    }
}
class Implementation2 implements Service{

    Implementation2(){}
    @Override
    public void method1() {
        System.out.println("Implementation2 method1");
    }

    @Override
    public void method2() {
        System.out.println("Implementation2 method2");
    }
}
class Implementation2Factory implements ServiceFactory{

    @Override
    public Service getService() {
        return new Implementation2();
    }
}

public class Factories {
    public static void serviceConsumer(ServiceFactory factory){
        Service service = factory.getService();
        service.method1();
        service.method2();
    }

    public static void main(String[] args) {
        serviceConsumer(new Implementation1Factory());
        serviceConsumer(new Implementation2Factory());
    }
}
//output
/*
Implementation1 method1
Implementation1 method2
Implementation2 method1
Implementation2 method2
*/
祝进步

猜你喜欢

转载自blog.csdn.net/zhaohancsdn/article/details/88775890