设计模式七大原则-接口隔离原则InterfaceSegregation

接口隔离原则:

客户端不应该依赖它不需要的接口,即一个类对另一个类的依赖应该建立在最小的接口上

案例:

类A通过接口Interface1依赖类B,类C通过接口Interface1依赖类D,如果接口Interface1对于类A和类c来说不是最小接口,那么类B和类D必须去实现他们不需要的方法(造成浪费)。

java 复制代码
public class interfaceSegregation {
    public static void main(String[] args) {
        A a = new A();
        a.depend1(new B());
        a.depend2(new B());
        a.depend3(new B());

        C c = new C();
        c.depend1(new D());
        c.depend4(new D());
        c.depend5(new D());

    }
}

interface interface1{
    void method1();
    void method2();
    void method3();
    void method4();
    void method5();
}

class B implements interface1{

    @Override
    public void method1() {
        System.out.println("B实现了method1");
    }

    @Override
    public void method2() {
        System.out.println("B实现了method2");
    }

    @Override
    public void method3() {
        System.out.println("B实现了method3");
    }

    @Override
    public void method4() {
        System.out.println("B实现了method4");
    }

    @Override
    public void method5() {
        System.out.println("B实现了method5");
    }
}

class D implements interface1{

    @Override
    public void method1() {
        System.out.println("D实现了method1");
    }

    @Override
    public void method2() {
        System.out.println("D实现了method2");
    }

    @Override
    public void method3() {
        System.out.println("D实现了method3");
    }

    @Override
    public void method4() {
        System.out.println("D实现了method4");
    }

    @Override
    public void method5() {
        System.out.println("D实现了method5");
    }
}

 class A {
    void depend1(interface1 interface1){
        interface1.method1();
    }
     void depend2(interface1 interface1){
         interface1.method2();
     }
     void depend3(interface1 interface1){
         interface1.method3();
     }
 }

 class C {
     void depend1(interface1 interface1){
         interface1.method1();
     }
     void depend4(interface1 interface1){
         interface1.method4();
     }
     void depend5(interface1 interface1){
         interface1.method5();
     }

 }

按隔离原则应当这样处理:将接口Interface1拆分为独立的几个接口,类A和类C分别与他们需要的接口建立依赖关系。也就是采用接口隔离原则。

按照实际情况将Interface1分为Interface1、Interface2、Interface3 等,代码略。

在项目中常见的业务类直接依赖另外一个业务类的时候往往也是违背接口隔离原则的,在实际项目中,出于开发速度、维护成本等原因,通常不会过于细化接口。

相关推荐
是2的10次方啊8 分钟前
🎭 程序员的一天:12种设计模式藏在你身边
设计模式
MediaTea10 分钟前
Python:接口隔离原则(ISP)
开发语言·网络·python·接口隔离原则
郝学胜-神的一滴13 分钟前
使用Qt OpenGL开发俄罗斯方块:从零到一实现经典游戏
c++·qt·程序人生·游戏·设计模式·系统架构·图形渲染
明洞日记14 分钟前
【设计模式手册018】访问者模式 - 分离数据结构与操作
数据结构·设计模式·访问者模式
有一个好名字1 小时前
设计模式-适配器模式
设计模式·适配器模式
好学且牛逼的马1 小时前
Apache Commons DbUtils
java·设计模式·apache
明洞日记1 小时前
【设计模式手册019】状态模式 - 管理对象状态转换
java·设计模式·状态模式
syt_10131 小时前
设计模式之-发布订阅者模式
设计模式
Yu_Lijing1 小时前
基于C++的《Head First设计模式》笔记——策略模式
c++·笔记·设计模式
sg_knight1 小时前
设计模式与代码重构
python·设计模式·重构·开发