设计模式七大原则-接口隔离原则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 等,代码略。

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

相关推荐
Shadow(⊙o⊙)16 小时前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki1 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅661 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa2 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio
sarasuki2 天前
如何让 Agent 获取更多的能力?插件 / 技能系统
人工智能·设计模式·agent
sarasuki2 天前
如何让 Agent 安全运行你的命令 :命令分级 + Hook + 读写锁
人工智能·设计模式·agent
Zane19942 天前
技术不难,为什么项目却越改越不敢动?聊聊复杂系统开发该怎么想
设计模式
geovindu2 天前
rust: Factory Method Pattern
开发语言·设计模式·rust·工厂方法模式·创建型模式
一木 之林2 天前
第 8 节 C++ 设计模式在 AI 推理 SDK 和 Agent 工具运行时中如何落地
c++·人工智能·设计模式
Zane19943 天前
MVC 三层架构被打上反模式标签?一次账户扣款需求,讲清楚贫血模型和充血模型该怎么选
设计模式