蘇阿細 - 接口隔离原则
type: channel
link: https://www.wangchouchou.com/tag/%E6%8E%A5%E5%8F%A3%E9%9A%94%E7%A6%BB%E5%8E%9F%E5%88%99/
items: 接口隔离原则

接口隔离原则
type: item
date: 2022-08-22T15:16:00+00:00
description: 定义：客户端不应该被迫依赖于它不使用的方法，即：一个类对另一个类的依赖应该建立在最小的接口上以安全门为例：存在的问题：如果要增加新的品牌的安全门，则违背了开闭原则SafetyDoorpublic interface SafetyDoor { /** * 防盗 */ void antiTheft(); /** * 防火 */ void fireproof(); /** * 防水 */ void waterproof(); }TestSafetyDoorpublic class TestSafetyDoor implements SafetyDoor { @Override public void antiTheft() { System.out.println("防盗"); } @Override public void fireproof() { System.out.println("防火"); } @Override public void waterproof() { System.out.println("防水"); } }Clientpublic class Client { public static void main(String[] args) { //存在的问题：如果要增加新的品牌的安全门，则违背了开闭原则 TestSafetyDoor testSafetyDoor = new TestSafetyDoor(); testSafetyDoor.antiTheft(); testSafetyDoor.fireproof(); testSafetyDoor.waterproof(); } }改进：抽象出安全门各个功能的接口，新增其他品牌的安全门时只需实现对应功能的接口AntiTheftpublic interface AntiTheft { /** * 防盗 */ void antiTheft(); }Fireproofpublic interface Fireproof { /** * 防火 */ void fireproof(); }Waterproofpublic interface Waterproof { /** * 防水 */ void waterproof(); }TestSafetyDoorpublic class TestSafetyDoor implements AntiTheft, Fireproof, Waterproof { @Override public void antiTheft() { System.out.println("防盗"); } @Override public void fireproof() { System.out.println("防火"); } @Override public void waterproof() { System.out.println("防水"); } }Test01SafetyDoorpublic class Test01SafetyDoor implements AntiTheft, Fireproof { @Override public void antiTheft() { System.out.println("防盗"); } @Override public void fireproof() { System.out.println("防火"); } }Clientpublic class Client { public static void main(String[] args) { //Test品牌安全门 TestSafetyDoor testSafetyDoor = new TestSafetyDoor(); testSafetyDoor.antiTheft(); testSafetyDoor.fireproof(); testSafetyDoor.waterproof(); System.out.println("================="); //Test品牌安全门 Test01SafetyDoor test01SafetyDoor = new Test01SafetyDoor(); test01SafetyDoor.antiTheft(); test01SafetyDoor.fireproof(); } }