圖解Java設計模式之設計模式七大原則

2.1 設計模式的目的

編寫軟件過程當中,程序員面臨着來自耦合性,內聚性以及可維護性,可擴展性,重用性,靈活性等多方面的挑戰,設計模式是爲了讓程序(軟件)。具備更好
1)代碼重用性(即:相同功能的代碼,不用屢次編寫)
2)可讀性(即:編程規範性,便於其餘程序員的閱讀和理解)
3)可擴展性(即:當須要增長新的功能時,很是的方便,稱爲可維護)
4)可靠性(即:當咱們增長新的功能後,對原來的功能沒有影響)
5)使程序呈現高內聚,低耦合的特性
6)設計模式包含了面向對象的精髓,「懂了設計模式,你就懂了面向對象分析和設計(OOA/D)的精要「
7)Scott Mayers 在其鉅著《Effective C++》就曾經說過 :C++老手和C++新手的區別就是前者手背上有不少傷疤java

2.2 設計模式七大原則

設計模式原則,其實就是程序員在編程時,應當遵照的原則,也是各類設計模式的基礎(即:設計模式爲何這樣設計的依據)
設計模式經常使用的七大原則有 :
1)單一職責原則
2)接口隔離原則
3)依賴倒轉(倒置)原則
4)里氏替換原則
5)開閉原則
6)迪米特法則
7)合成複用原則程序員

2.3 單一職責原則

2.3.1 基本介紹

對類來講的,即一個類應該只負責一項職責。如類A負責兩個不一樣職責 :職責1,職責2。當職責1需求變動而改變A時,可能形成職責2執行錯誤,因此須要將類A的粒度分解爲A1,A2編程

2.3.2 應用實例

以交通工具案例講解設計模式

package com.example.testdemo.mode.principle; public class SingleResponsibility1 { public static void main(String[] args) { Vehicle vehicle = new Vehicle(); vehicle.run("摩托車"); vehicle.run("汽車"); vehicle.run("飛機"); } } // 交通工具類 /** * 方式1 : * 1 。 在方式1的run方法中,違反了單一職責原則 * 2 。 解決的方案很是第二季簡單,根據交通工具運行方法不一樣,分解成不一樣類便可 */ class Vehicle { public void run(String vehicle) { System.out.println(vehicle + " 在公路上運行。。。。。"); } } package com.example.testdemo.mode.principle; public class SingleResponsibility2 { public static void main(String[] args) { ReadVehicle readVehicle = new ReadVehicle(); readVehicle.run("摩托車"); readVehicle.run("汽車"); AirVehicle airVehicle = new AirVehicle(); airVehicle.run("飛機"); WaterVehicle waterVehicle = new WaterVehicle(); waterVehicle.run("輪船"); } } /** * 方案2分析 : * 1 :遵照單一職責原則 * 2 :可是這樣改動大,即將類分解,同時修改客戶端 * 3 :改進 :直接修改Vehicle類,改動的代碼會比較少 =》方案3 * */ class ReadVehicle { public void run(String vehicle) { System.out.println(vehicle + "公路運行"); } } class AirVehicle { public void run(String vehicle) { System.out.println(vehicle + "天空運行"); } } class WaterVehicle { public void run(String vehicle) { System.out.println(vehicle + "水中運行"); } } package com.example.testdemo.mode.principle; public class SingleResponsibility3 { public static void main(String[] args) { Vehicle2 vehicle2 = new Vehicle2(); vehicle2.run("汽車"); vehicle2.runAir("飛機"); vehicle2.runWater("輪船"); } } /** * 方案3的分析 : * 1 :這種修改方法沒有對原來的類作大的修改,只是增長方法 * 2 :這裏雖然沒有在類這個級別上遵照單一職責原則,可是在方法級別上,仍然是遵照單一職責 */ class Vehicle2 { public void run(String vehicle) { System.out.println(vehicle + " 在公路上運行。。。。。"); } public void runAir(String vehicle) { System.out.println(vehicle + " 在天空上運行。。。。。"); } public void runWater(String vehicle) { System.out.println(vehicle + " 在水中運行。。。。。"); } } 

單一職責原則注意事項和細節
(1) 下降類的複雜度,一個類只負責一項職責。
(2)提升類的可讀性,可維護性。
(3)下降變動引發的風險。
(4)一般狀況下,咱們應當遵照單一職責原則,只有邏輯足夠簡單,才能夠在代碼級違反單一職責原則 :只有類中方法數量足夠少,能夠在方法級別保存單一職責原則。緩存

2.4 接口隔離原則(Interface Segregation Principle)

2.4.1 基本介紹

(1)客戶端不該該依賴它不須要的接口,即一個類對另外一個類的依賴應該創建在最小的接口上
(2)先看一張圖
在這裏插入圖片描述
(3)類A經過接口Interface1依賴類B,類C經過接口Interface1依賴類D,若是接口Interface1對於類A和類C來講不是最小接口,那麼類B和類C必須去實現他們不須要的方法。
(4)按隔離原則應當這樣處理 :
將接口Interface1拆分爲獨立的幾個接口(這裏咱們拆分3個接口),類A和類C分別與他們須要的接口創建依賴關係,也就是採用接口隔離原則微信

2.4.2 應用實例

1)類A經過接口Interface1依賴類B,類C經過接口Interface1依賴類D。
2)沒有使用接口隔離原則的代碼架構

package com.example.testdemo.mode.principle.segregation; import io.swagger.models.auth.In; public class Segregation1 { public static void main(String[] args) { } } /** * 接口 */ interface Interface1 { void operation1(); void operation2(); void operation3(); void operation4(); void operation5(); } class B implements Interface1 { @Override public void operation1() { System.out.println(" B 實現了 operation1"); } @Override public void operation2() { System.out.println(" B 實現了 operation2"); } @Override public void operation3() { System.out.println(" B 實現了 operation3"); } @Override public void operation4() { System.out.println(" B 實現了 operation4"); } @Override public void operation5() { System.out.println(" B 實現了 operation5"); } } class D implements Interface1 { @Override public void operation1() { System.out.println(" D 實現了 operation1"); } @Override public void operation2() { System.out.println(" D 實現了 operation2"); } @Override public void operation3() { System.out.println(" D 實現了 operation3"); } @Override public void operation4() { System.out.println(" D 實現了 operation4"); } @Override public void operation5() { System.out.println(" D 實現了 operation5"); } } /** * A 類經過接口Interface1 依賴(使用)B類,可是隻會用到1,2,3方法 */ class A { public void depend1(Interface1 interface1) { interface1.operation1(); } public void depend2(Interface1 interface1) { interface1.operation2(); } public void depend3(Interface1 interface1) { interface1.operation3(); } } /** * C 類經過接口Interface1 依賴(使用)D類,可是隻會用到1,4,5方法 */ class C { public void depend1(Interface1 interface1) { interface1.operation1(); } public void depend4(Interface1 interface1) { interface1.operation4(); } public void depend5(Interface1 interface1) { interface1.operation5(); } } 
  • 應傳統方法的問題和接口隔離原則改進
    (1)類A經過Interface1依賴類B,類C經過接口Interface1依賴類D,若是接口Interface1對於類A和類C來講不是最小接口,那麼類B和類C必須去實現他們不須要的方法。
    (2)將接口Interface1拆分爲獨立的幾個接口,類A和類C分別與他們須要的接口創建依賴關係。也就是採用接口隔離原則。
    (3)接口Interface1中出現的方法,根據實際狀況拆分爲三個接口
    (4)代碼實現
    在這裏插入圖片描述
package com.example.testdemo.mode.principle.segregation1; public class Segregation2 { public static void main(String[] args) { // 使用一把 A a = new A(); // A 類經過接口去依賴B類 a.depend1(new B()); a.depend2(new B()); a.depend3(new B()); // C 類經過接口去依賴(使用)D類 C c = new C(); c.depend1(new D()); c.depend4(new D()); c.depend5(new D()); } } /** * 接口 */ interface Interface1 { void operation1(); } interface Interface2 { void operation2(); void operation3(); } interface Interface3 { void operation4(); void operation5(); } class B implements Interface1, Interface2 { @Override public void operation1() { System.out.println(" B 實現了 operation1"); } @Override public void operation2() { System.out.println(" B 實現了 operation2"); } @Override public void operation3() { System.out.println(" B 實現了 operation3"); } } class D implements Interface1, Interface3 { @Override public void operation1() { System.out.println(" D 實現了 operation1"); } @Override public void operation4() { System.out.println(" D 實現了 operation4"); } @Override public void operation5() { System.out.println(" D 實現了 operation5"); } } /** * A 類經過接口Interface1 ,Interface2 依賴(使用)B類,可是隻會用到1,2,3方法 */ class A { public void depend1(Interface1 interface1) { interface1.operation1(); } public void depend2(Interface2 interface1) { interface1.operation2(); } public void depend3(Interface2 interface1) { interface1.operation3(); } } /** * C 類經過接口Interface1 ,Interface3 依賴(使用)D類,可是隻會用到1,4,5方法 */ class C { public void depend1(Interface1 interface1) { interface1.operation1(); } public void depend4(Interface3 interface1) { interface1.operation4(); } public void depend5(Interface3 interface1) { interface1.operation5(); } } 

2.5 依賴倒轉原則

2.5.1 基本介紹

依賴倒轉原則(Dependence Inversion Principle)是指 :
(1)高層模塊不該該依賴底層模塊,兩者都應該依賴其抽象
(2)抽象不該該依賴細節,細節應該依賴抽象
(3)依賴倒轉(倒置)的中心思想是面向接口編程
(4)依賴倒轉原則是基於這樣的設計理念 :相對於細節的多變性,抽象的東西要穩定的多。以抽象爲基礎搭建的架構比以細節爲基礎的架構要穩定的多。在java中,抽象指的是接口或抽象類,細節就是具體的實現類。
(5)使用接口或抽象類的目的是制定好規範,而不涉及任何具體的操做,把展現細節的任務交給他們的實現類去完成。框架

2.5.2 應用實例

1)方案1 + 分析說明ide

package com.example.testdemo.mode.principle.inversion; public class DependecyInversion { public static void main(String[] args) { Person person = new Person(); person.receive(new Email()); } } class Email { public String getInfo() { return "電子郵件信息 :hello,world"; } } /** * 完成Person接收消息的功能 * 方式1分析 * 1。簡單,比較容易想到 * 2。若是咱們獲取的對象是微信,短信等等,則新增類,同時Persons也要增長相應的接收方法 * 3。解決思路 :引入一個抽象的接口IReceiver,表示接收者,這樣Person類與接口IReceiver發生依賴 * 由於Email,微信等等屬於接收的範圍,他們各自實現IReceiver接口就ok,這樣咱們就符合依賴倒轉原則 */ class Person { public void receive(Email email) { System.out.println(email.getInfo()); } } 

2)方案2(依賴倒轉)+ 分析說明函數

package com.example.testdemo.mode.principle.inversion.inprove; public class DependecyInversion { public static void main(String[] args) { // 客戶端無需改變 Person person = new Person(); person.receive(new Email()); person.receive(new WeiXin()); } } /** * 定義接口 */ interface IReceiver { String getInfo(); } class Email implements IReceiver{ @Override public String getInfo() { return "電子郵件信息 :hello,world"; } } /** * 增長微信 */ class WeiXin implements IReceiver { @Override public String getInfo() { return "微信消息 :hello ok"; } } /** * 方式2 */ class Person { /** * 這裏是咱們對接口的依賴 * @param iReceiver */ public void receive(IReceiver iReceiver) { System.out.println(iReceiver.getInfo()); } } 

依賴關係傳遞的三種方式 :
1)接口傳遞
2)構造方法傳遞
3)setter方法傳遞

package com.example.testdemo.mode.principle.inversion.inprove; public class Dependecy { public static void main(String[] args) { IOpenAndClose iOpenAndClose = new OpenAndClose(); iOpenAndClose.open(new ChangHong()); IOpenAndClose2 iOpenAndClose2 = new OpenAndClose2(new XiaoMi()); iOpenAndClose2.open(); IOpenAndClose3 iOpenAndClose3 = new OpenAndClose3(); iOpenAndClose3.setTv(new SanXing()); iOpenAndClose3.open(); } } /** * 方式1 :經過接口傳遞實現依賴 */ interface IOpenAndClose { /** * 抽象方法,接收接口 * @param tv */ void open(ITV tv); } /** * ITV接口 */ interface ITV { void play(); } class ChangHong implements ITV { @Override public void play() { System.out.println("長虹電視機打開"); } } /** * 實現接口 */ class OpenAndClose implements IOpenAndClose { @Override public void open(ITV tv) { tv.play(); } } /** * 方式2 :經過構造方法依賴傳遞 */ interface IOpenAndClose2 { /** * 抽象方法 */ void open(); } /** * ITV接口 */ interface ITV2 { void play(); } class XiaoMi implements ITV2 { @Override public void play() { System.out.println("小米電視機打開"); } } class OpenAndClose2 implements IOpenAndClose2 { /** * 成員屬性 */ public ITV2 tv; /** * 構造方法 * @param itv2 */ public OpenAndClose2(ITV2 itv2) { this.tv = itv2; } @Override public void open() { this.tv.play(); } } /** * 方式3,經過setter方法傳遞 */ interface IOpenAndClose3 { /** * 抽象方法 */ void open(); void setTv(ITV3 tv); } /** * ITV接口 */ interface ITV3 { void play(); } class SanXing implements ITV3 { @Override public void play() { System.out.println("三星電視打開"); } } class OpenAndClose3 implements IOpenAndClose3 { private ITV3 itv3; @Override public void open() { this.itv3.play(); } @Override public void setTv(ITV3 tv) { this.itv3 = tv; } } 

依賴倒轉原則的注意事項和細節
1)底層模塊盡力都要有抽象類或接口,或者二者都有,程序穩定性更好。
2)變量的聲明類型儘可能是抽象類或接口,這樣咱們的變量引用和實際對象間,就存在一個緩存層,利於程序擴展和優化。
3)繼承時遵循里氏替換原則。

2.6 里氏替換原則

2.6.1 OO中的繼承性的思考和說明

1)繼承包含這樣一層含義 :父類中凡是已經實現好的方法,其實是在設定規範和契約,雖然它不強制要求全部的子類必須遵循這些契約,可是若是子類對象這些已經實現的方法任意修改,就會對整個繼承體系形成破壞。
2)繼承在給程序設計帶來便利的同時,也帶來類弊端。好比使用繼承會給程序帶來侵入性,程序的可移植性下降,增長對象間的耦合性,若是一個類被其餘的類所繼承,則當這個類須要修改時,必須考慮到全部的子類,而且父類修改後,全部涉及到子類的功能都有可能產生故障。
3)問題提出 :在編程中,如何正確的使用繼承?=》里氏替換原則

2.6.2 基本介紹

1)里氏替換原則(Liskov Substitution Principle)在1988年,由麻省理工學院的一位姓裏的女士提出的。
2)若是對每一個類型爲T1的對象O1,都有類型爲T2的對象O2,使得以T1定義的全部程序P在全部的對象O1都代換成O2時,程序P的行爲沒有變化,那麼類型T2是類型T1的子類型。換句話說,全部引用基類的地方必須能透明地使用其子類的對象。
3)在使用繼承時,遵循里氏替換原則,在子類中儘可能不要重寫父類的方法。
4)里氏替換原則告訴咱們,繼承實際上讓兩個類耦合性加強了,在適當的狀況下,能夠經過聚合、組合、依賴來解決問題。

2.6.3 一個程序引出的問題和思考

該看個程序,思考下問題和解決思路

package com.example.testdemo.mode.principle.liskov; public class Liskov { public static void main(String[] args) { A a = new A(); System.out.println("11 - 3 = " + a.funcl(11, 3)); System.out.println("1 - 8 = " + a.funcl(1, 8)); System.out.println("-----------------"); B b = new B(); // 這裏本意是求出11 - 3 System.out.println("11 - 3 = " + b.funcl(11, 3)); // 1 - 8 System.out.println("1 - 8 = " + b.funcl(1, 8)); System.out.println("11 + 3 + 9 = " + b.func2(11, 3)); } } class A { /** * 返回兩個數的差 * * @param num1 * @param num2 * @return */ public int funcl(int num1, int num2) { return num1 - num2; } } /** * B類繼承類A * * 增長類一個新功能 :完成兩個數相加,而後和9 求和 */ class B extends A { /** * 這裏,重寫類A類的方法,多是無心識 * @param a * @param b * @return */ @Override public int funcl(int a, int b) { return a + b; } public int func2(int a, int b) { return funcl(a, b) + 9; } } 

2.6.4 解決方法

1)咱們發現原來運行正常的相減功能發生類錯誤。緣由就是類B無心中重寫父類的方法,形成原有功能出現錯誤。在實際編程中,咱們經常會經過重寫父類的方法完成新的功能,這樣寫起來雖然簡單,但整個繼承體系的複用性會比較差。特別是運行多態比較頻繁的時候。
2)通用的作法是 :原來的父類和子類都繼承一個更通俗的基類,原有的繼承關係去掉,採用依賴、聚合、組合等關係代替。
3)改進方案。
在這裏插入圖片描述

package com.example.testdemo.mode.principle.improve; public class Liskov { public static void main(String[] args) { A a = new A(); System.out.println("11 - 3 = " + a.func1(11, 3)); System.out.println("1 - 8 = " + a.func1(1, 8)); System.out.println("--------------------------"); B b = new B(); // 由於B類再也不繼承A類,所以調用者,不會再funcl是求減法 // 調用完成的功能就會很明確 // 這裏本意是求出 11 + 3 System.out.println("11 + 3 = " + b.func1(11, 3)); // 1 + 8 System.out.println("1 + 8 = " + b.func1(1, 8)); System.out.println("11 + 3 + 9 = " + b.func2(11, 3)); // 使用組合仍然可使用到A類相關方法 // 這裏本意是求出 11 - 3 System.out.println("11 - 3 = " + b.func3(11, 3)); } } /** * 建立一個更加基礎的基類 */ class Base { // 把更加基礎的方法和成員寫Base類 } /** * A 類 */ class A extends Base { /** * 返回兩個數的差 * @param num1 * @param num2 * @return */ public int func1(int num1, int num2) { return num1 - num2; } } /** * B類 繼承了 A * * 增長類一個新功能 :完成兩個數相加,而後和9 求和 */ class B extends Base { /** * 若是B須要使用A類的方法,使用組合關係 */ private A a = new A(); /** * 這裏,重寫了A類方法,多是無心識 * * @param a * @param b * @return */ public int func1(int a, int b) { return a + b; } public int func2(int a, int b) { return func1(a, b) + 9; } /** * 咱們仍然想使用A的方法 * @param a * @param b * @return */ public int func3(int a, int b) { return this.a.func1(a,b); } } 

2.7 開閉原則

2.7.1 基本介紹

1)開閉原則(Open Closed Principle)是編程中最基礎、最重要的設計原則
2)一個軟件實體如類,模塊和函數應該對擴展開放(對提供方),對修改關閉(對使用方)。用抽象構建框架,用實現擴展細節。
3)當軟件須要變化時,儘可能經過擴展軟件實體的行爲來實現變化,而不是經過修改已有的代碼來實現變化。
4)編程中遵循其它原則,以及使用設計模式的目的就是遵循開閉原則。

2.7.2 看下面一段代碼

看一個畫圖形的功能。
類圖設計,以下 :
在這裏插入圖片描述

package com.example.demo.ocp;

public class Ocp {

    public static void main(String[] args) {
		 // 使用可靠存在的問題
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
        graphicEditor.drawShape(new Triangle());
    }

}

/**
 * 這是一個用於繪圖的類(使用方)
 */
class GraphicEditor {

    /**
     * 接收Shape對象,而後根據type,來繪製不一樣的圖形
     * @param shape
     */
    public void drawShape(Shape shape) {
        if (shape.m_type == 1) {
            drawRectangle(shape);
        } else if (shape.m_type == 2) {
            drawCircle(shape);
        } else if (shape.m_type == 3) {
            drawTriangle(shape);
        }
    }

    /**
     * 繪製三角形
     * @param shape
     */
    private void drawTriangle(Shape shape) {
        System.out.println("繪製三角形");
    }

    /**
     * 繪製圓形
     * @param shape
     */
    private void drawCircle(Shape shape) {
        System.out.println("繪製圓形");
    }


    /**
     * 繪製矩形
     * @param shape
     */
    private void drawRectangle(Shape shape) {
        System.out.println("繪製矩形");
    }

}

/**
 * Shape類,基類
 */
class Shape {
    int m_type;
}

class Rectangle extends Shape {
    Rectangle() {
        super.m_type = 1;
    }
}

class Circle extends Shape {

    Circle() {
        super.m_type = 2;
    }
}

/**
 * 新增畫三角形
 */
class Triangle extends Shape {
    Triangle() {
        super.m_type = 3;
    }
}

2.7.3 方式1的優缺點

1)優勢是比較好理解,簡單易操做。
2)缺點是違反了設計模式的ocp原則,即對擴展開放(提供方),對修改關閉(使用方)。即當咱們給類增長新功能的時候,儘可能不修改代碼,或者儘量少修改代碼。
3)好比咱們這時要新增長一個圖形種類 三角形,咱們須要作不少修改,修改的地方比較多。

2.7.4 改進的思路分析

思路 : 把建立Shape類作成抽象類,並提供一個抽象的draw方法,讓子類去實現便可,這樣咱們有新的圖形種類時,只須要讓新的圖形類繼承Shape,並實現draw方法便可,使用方的代碼就不須要修改 -》
知足了開閉原則
改進後的代碼 :

package com.example.demo.ocp.improve;

public class Ocp {
    public static void main(String[] args) {
        // 使用看看存在的問題
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
        graphicEditor.drawShape(new Triangle());
        graphicEditor.drawShape(new OtherGraphic());
    }
}

/**
 * 這是一個用於繪圖的類(使用方)
 */
class GraphicEditor {

    /**
     * 接收Shape對象,調用draw方法
     * @param shape
     */
    public void drawShape(Shape shape) {
        shape.draw();
    }
}

/**
 * Shape類,基類
 */
abstract class Shape {
    int m_type;

    /**
     * 抽象方法
     */
    public abstract void draw();
}

class Rectangle extends Shape {

    Rectangle() {
        super.m_type = 1;
    }

    @Override
    public void draw() {
        System.out.println("繪製矩形");
    }
}

class Circle extends Shape {

    Circle() {
        super.m_type = 2;
    }

    @Override
    public void draw() {
        System.out.println("繪製圓形");
    }
}

/**
 * 新增畫三角形
 */
class Triangle extends Shape {

    Triangle() {
        super.m_type = 3;
    }

    @Override
    public void draw() {
        System.out.println("繪製三角形");
    }
}

/**
 * 新增一個圖形
 */
class OtherGraphic extends Shape {

    OtherGraphic() {
        super.m_type = 4;
    }

    @Override
    public void draw() {
        System.out.println("繪製其餘圖形");
    }
}

2.8 迪米特法則

2.8.1 基本介紹

1)一個對象應該對其餘對象保持最少的瞭解。
2)類與類關係越密切,耦合度越大。
3)迪米特法則(Demeter Principle)又叫最少知道原則,即一個類對本身依賴的類知道的越少越好。也就是說,對於被依賴的類無論多麼複雜,都儘可能將邏輯封裝在類的內部。對外除了提供的public方法,不對外泄露任何信息。
4)迪米特法則還有個簡單的定義 :只與直接的朋友通訊。
5)直接的朋友 :每一個對象都會與其餘對象有耦合關係,只要兩個對象之間有耦合關係,咱們就說這兩個對象之間是朋友關係。耦合的方式不少,依賴、關聯組合、聚合等。其中,咱們稱出現成員變量,方法參數,方法返回值中的類爲直接的朋友,而出如今局部變量中的類不是直接的朋友。也就是說,陌生的類最好不要以局部變量的形式出如今類的內部。

2.8.2 應用實例

1)有一個學校,下屬有各個學院和總部,現要求打印出學校總部員工ID和學院員工的id
2)編程實現上面的功能,看代碼演示
3)代碼演示

package com.example.demo.demeter;

import java.util.ArrayList;
import java.util.List;

/**
 * 客戶端
 */
public class Demeter1 {

    public static void main(String[] args) {
        // 建立一個 SchoolManager 對象
        SchoolManager schoolManager = new SchoolManager();
        // 輸出學院的員工id 和 學院總部的員工信息
        schoolManager.printAllEmployee(new CollegeManager());
    }

}

/**
 * 學校總部員工類
 */
class Employee {

    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

/**
 * 學院的員工類
 */
class CollegeEmployee {

    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

/**
 * 管理學院員工的管理類
 */
class CollegeManager {

    /**
     * 返回學院的全部員工
     * @return
     */
    public List<CollegeEmployee> getAllEmployee() {
        List<CollegeEmployee> employees = new ArrayList<>();
        // 這裏咱們增長了10個員工到list
        for (int i = 0; i < 10; i++) {
            CollegeEmployee collegeEmployee = new CollegeEmployee();
            collegeEmployee.setId("學院員工 id = " + i);
            employees.add(collegeEmployee);
        }
        return employees;
    }
}

/**
 * 學校管理類
 *
 * 分析 SchoolManager 類的直接朋友類有哪些 Employee、CollegeManager
 * CollegeEmployee 不是 直接朋友,而是一個陌生類,這樣違背了迪米特法則
 *
 */
class SchoolManager {

    /**
     * 返回學校總部的員工
     * @return
     */
    public List<Employee> getAllEmployee() {
        List<Employee> list = new ArrayList<>();
        // 這裏咱們增長了5個員工到list
        for (int i = 0; i < 5; i++) {
            Employee employee = new Employee();
            employee.setId("學校總部員工 id = " + i);
            list.add(employee);
        }
        return list;
    }

    /**
     * 該方法完成輸出學校總部和學院員工信息 (id)
     * @param collegeManager
     */
    void printAllEmployee(CollegeManager collegeManager) {
        // 分析問題
        // 1. 這裏的 CollegeEmployee 不是 SchoolManageer的直接朋友
        // 2. CollegeEmployee 是以局部變量方式出如今 SchoolManager
        // 3. 違反了 迪米特法則
        // 獲取到學院員工
        List<CollegeEmployee> allEmployee = collegeManager.getAllEmployee();
        System.out.println("-------------學院員工-------------");
        for (CollegeEmployee collegeEmployee : allEmployee) {
            System.out.println(collegeEmployee.getId());
        }
        // 獲取到學院總部員工
        List<Employee> employee = this.getAllEmployee();
        System.out.println("-----------學校總部員工-------------");
        for (Employee employee1 : employee) {
            System.out.println(employee1.getId());
        }
    }
}

2.8.3 應用實例改進

1)前面設計的問題在於SchoolManager中,CollegeEmployee類並非SchoolManager類的直接朋友(分析)
2)按照迪米特法則,應該避免類中出現這樣非直接朋友關係的耦合
3)對代碼按照迪米特法則進行改進。
4)代碼演示

package com.example.demo.demeter.improve;

import java.util.ArrayList;
import java.util.List;

/**
 * 客戶端
 */
public class Demeter1 {

    public static void main(String[] args) {
        // 建立一個 SchoolManager 對象
        SchoolManager schoolManager = new SchoolManager();
        // 輸出學院的員工id 和 學院總部的員工信息
        schoolManager.printAllEmployee(new CollegeManager());
    }

}

/**
 * 學校總部員工類
 */
class Employee {

    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

/**
 * 學院的員工類
 */
class CollegeEmployee {

    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

/**
 * 管理學院員工的管理類
 */
class CollegeManager {

    /**
     * 返回學院的全部員工
     * @return
     */
    public List<CollegeEmployee> getAllEmployee() {
        List<CollegeEmployee> employees = new ArrayList<>();
        // 這裏咱們增長了10個員工到list
        for (int i = 0; i < 10; i++) {
            CollegeEmployee collegeEmployee = new CollegeEmployee();
            collegeEmployee.setId("學院員工 id = " + i);
            employees.add(collegeEmployee);
        }
        return employees;
    }

    /**
     * 輸出學院員工的信息
     */
    public void printEmployee() {
        // 獲取到學院員工
        List<CollegeEmployee> allEmployee = getAllEmployee();
        System.out.println("----------學院員工-----------");
        for (CollegeEmployee collegeEmployee : allEmployee) {
            System.out.println(collegeEmployee.getId());
        }
    }
}

/**
 * 學校管理類
 *
 * 分析 SchoolManager 類的直接朋友類有哪些 Employee、CollegeManager
 * CollegeEmployee 不是 直接朋友,而是一個陌生類,這樣違背了迪米特法則
 *
 */
class SchoolManager {

    /**
     * 返回學校總部的員工
     * @return
     */
    public List<Employee> getAllEmployee() {
        List<Employee> list = new ArrayList<>();
        // 這裏咱們增長了5個員工到list
        for (int i = 0; i < 5; i++) {
            Employee employee = new Employee();
            employee.setId("學校總部員工 id = " + i);
            list.add(employee);
        }
        return list;
    }

    /**
     * 該方法完成輸出學校總部和學院員工信息 (id)
     * @param collegeManager
     */
    void printAllEmployee(CollegeManager collegeManager) {
        // 分析問題
        // 1. 將輸出學院的員工方法,封裝到CollegeManager
        collegeManager.printEmployee();
        // 獲取到學院總部員工
        List<Employee> employee = this.getAllEmployee();
        System.out.println("-----------學校總部員工-------------");
        for (Employee employee1 : employee) {
            System.out.println(employee1.getId());
        }
    }
}

2.8.4 迪米特法則注意事項和細節

1)迪米特法則的核心是下降類之間的耦合
2)可是注意 :因爲每一個類都減小了沒必要要的依賴,所以迪米特法則只是要求下降類間(對象間)耦合關係,並非要求徹底沒有依賴關係。

2.9 合成複用原則(Composite Reuse Principle)

基本介紹 :原則是儘可能使用合成/聚合的方式,而不是使用繼承。
在這裏插入圖片描述

設計原則核心思想

1)找出應用中可能須要變換之處,把它們獨立出來,不要和那些須要變化的代碼混在一塊兒。2)針對接口編程,而不是針對實現編程。3)爲了交互對象之間的鬆耦合設計而努力。

相關文章
相關標籤/搜索