面向接口編程,依賴於抽象而不是依賴與具體類,寫具體類時經過接口進行交互
1. 基本介紹java
(1)高層模塊不該該依賴低層模塊,兩者都應該依賴抽象 (2)抽象不該該依賴細節,細節應該依賴抽象 (3)依賴倒置的中心思想是面向接口編程 (4)依賴倒置原則的設計理念,相對於細節的多變性,抽象的東西要穩定的多,以抽象爲基礎搭建的框架比以細節爲基礎的框架穩定,java中,抽象表明接口或抽象類,細節表明具體的實現類 (5)使用接口的目的是制定好規範,不涉及具體的操做,把具體的細節交給實現類完成
2. 應用場景編程
完成Person 接收消息微信
/** * 完成Person 接收信息 * 一、若是須要接收別的信息時,須要新增類,同時Person 須要添加新的方法 * 二、解決思路: 定義一個接收的接口,person 類去實現, * 三、若是須要接收別的信息,新增類可直接實現接收接口,實現接收信息 */ static class Email { public String getInfo() { return "接收郵件信息"; } } static class Person { public void receive(Email email) { System.out.println(email.getInfo()); } } public static void main(String[] args) { Person person = new Person(); person.receive(new Email()); //改進 PersonInfo personInfo = new PersonInfo(); personInfo.receive(new WeChat()); } /** * 改進方案 接收郵件、微信消息 */ interface IReceive { public String getInfo(); } static class WeChat implements IReceive { @Override public String getInfo() { return "接收微信消息"; } } static class PersonInfo { //person 修改成對接口的依賴 public void receive(IReceive receive) { System.out.println(receive.getInfo()); } }`
3. 依賴傳遞的三種方式框架
公共的接口 interface ITv { public void play(); } static class ChangHong implements ITv { @Override public void play() { System.out.println("打開電視機-----"); } }
(1)經過接口傳遞ide
interface IOpen { public void open(ITv tv); } static class Open implements IOpen { @Override public void open(ITv tv) { tv.play(); } } public static void main(String[] args) { ChangHong changHong = new ChangHong(); Open open = new Open(); open.open(changHong); }`
(2)經過構造函數傳遞函數
interface IOpenAndClose { public void open(); } static class OpenAndClose implements IOpenAndClose { private ITv tv; //構造函數 public OpenAndClose(ITv tv) { this.tv = tv; } @Override public void open() { tv.play(); } } public static void main(String[] args) { ChangHong changHong = new ChangHong(); OpenAndClose openAndClose = new OpenAndClose(changHong); openAndClose.open(); }
(3)經過setter方法傳遞this
interface IOpenClose { public void open(); //set public void setOpen(ITv tv); } static class OpenClose implements IOpenClose { private ITv tv; @Override public void open() { this.tv.play(); } @Override public void setOpen(ITv tv) { this.tv = tv; } } public static void main(String[] args) { ChangHong changHong = new ChangHong(); OpenClose openClose = new OpenClose(); openClose.setOpen(changHong); openClose.open(); }