接口

关于接口

有抽象方法和全局常量组成的类称之为接口

使用原则:

  • 接口必须有子类,子类可以使用inplements关键字实现多个接口,避免单继承的局限性

  • 接口的子类必须覆写接口中全部的抽象方法

  • 可以利用子类对象向上转型实现实例化

  • 接口可以使用extends关键字同时继承多个父接口,但是不可以继承抽象类

  • 一个子类如果既要继承抽象类也要实现接口,应该先继承,后实现接口

接口的限制

  • 接口的限制要比抽象类的限制要少

  • 抽象类是单继承原则,但是接口可以多继承

  • 从概念上讲,接口由抽象方法和全局常量组成,但是也可以在接口里面定义普通内部类,抽象内部类,内部接口

  • 和抽象类类似,如果在接口的内部用static定义了一个内部接口,那么这个接口相当于一个外部接口

接口的实际应用——工厂设计模式(Factory)

忽略过程,直接得到结果,更少的修改客户端的代码

  • 如果不采用工厂设计模式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    interface {
    public void eat();
    }
    class Apple implements {
    public void eat() {
    System.out.println("吃苹果");
    }
    }
    public class testDemo3 {
    public static void main(String args[]) {
    Fruit f=new Apple();
    f.eat();
    }

    }

    如果客户端想要再增加一个吃橘子的类,那么就会修改客户端的代码,采用工厂设计模式就可以避免这种直接修改客户端的操作
    代码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    interface {
    public void eat();
    }
    class Apple implements {
    public void eat() {
    System.out.println("eat apple");
    }
    }
    class Orange implements {
    public void eat() {
    System.out.println("eat orange");
    }
    }
    class Factory{
    public static Fruit getIn 大专栏  接口stance(String className) {
    if("apple".equals(className)) {
    return new Apple();
    }
    if("orange".equals(className)){
    return new Orange();
    }
    else {
    return null;
    }
    }
    }
    public class testDemo3 {
    public static void main(String args[]) {
    Fruit f=Factory.getInstance("orange");
    f.eat();
    }

    }

接口的实际应用——代理设计模式(Proxy)

代理设计模式的实现——以代理上网为例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
interface Network{                   
public void browse(); //定义浏览抽象方法
}
class Real implements Network{ //真实上网操作
public void browse() { //覆写抽象方法
System.out.println("上网浏览");
}
}
class Proxy implements Network{ //代理上网
private Network network;
public Proxy(Network network) { //代理的真实操作
this.network=network;
}
public void check() { //具体上网相关的操作
System.out.println("检查用户合法性");
}
public void browse() {
this.check(); //调用与上网相关的具体操作
this.network.browse(); //调用真实上网操作
}
}
public class tesnDemo2{
public static void main(String args[]) {
Network net=null; //定义接口对象
net=new Proxy(new Real()); //实例化代理,同时传入代理的真实操作
net.browse();
}
}
原文地址:https://www.cnblogs.com/lijianming180/p/12026677.html