[ Java ] 一文搞懂設計模式常用的七大原則


一、單一職責原則

  • 降低類的複雜性,即一個類應該只負責一項職責。
  • 提高類的可讀性,可維護性
  • 降低變更引起的風險
  • 代碼邏輯比較簡單的情況下,可以在方法級別保持單一職責原則
  • 代碼示例
/**
* 完全符合單一職責原則
*/
public class Test {
    public static void main(String[] args) {
        Vehicle vehicle = new Vehicle();
        vehicle.run("汽車");

        Vehicle1 vehicle1 = new Vehicle1();
        vehicle1.run("飛機");
    }
}
class Vehicle{
    public void run(String vehicle){
        System.out.println(vehicle+":在地上跑!");
    }
}
class Vehicle1{
    public void run(String vehicle){
        System.out.println(vehicle+":在天上飛!");
    }
}
/**
* 方法級別的單一職責原則
*/
public class Test {
    public static void main(String[] args) {
        Vehicle vehicle = new Vehicle();
        vehicle.run("汽車");

        vehicle.runAir("飛機");
    }
}
class Vehicle{
    public void run(String vehicle){
        System.out.println(vehicle+":在地上跑!");
    }
    public void runAir(String vehicle){
        System.out.println(vehicle+":在天上飛!");
    }
}

二、接口隔離原則

  • 不應該依賴它不需要的接口,即一個類對另一個類的依賴應該建立在最小接口上

  • 代碼示例

/**
 * 違反接口隔離原則,代碼示例
 */
interface interface1{
    public void operation1();
    public void operation2();
    public void operation3();
}
class B implements interface1{

    public void operation1() {
        System.out.println("B 實現了 operation1");
    }

    public void operation2() {
        System.out.println("B 實現了 operation2");
    }

    public void operation3() {
        System.out.println("B 實現了 operation3");
    }
}
class D implements interface1{

    public void operation1() {
        System.out.println("D 實現了 operation1");
    }

    public void operation2() {
        System.out.println("D 實現了 operation2");
    }

    public void operation3() {
        System.out.println("D 實現了 operation3");
    }
}

/**
 * A 類 通過接口 interface1 依賴(使用)B 類,但是隻用到 1,2 方法
 */
class A{
    public void depend1(interface1 i){
        i.operation1();
    }
    public void depend2(interface1 i){
        i.operation2();
    }
}
/**
 * C 類 通過接口 interface1 依賴(使用)D 類,但是隻用到 1,3方法
 */
class C{
    public void depend1(interface1 i){
        i.operation1();
    }
    public void depend3(interface1 i){
        i.operation3();
    }
}
/**
 * 遵循接口隔離原則,代碼示例
 */
public class Test {
    public static void main(String[] args) {
        A a = new A();
        a.depend1(new B());
        a.depend2(new B());

        C d = new C();
        interface1 ii = new D();
        d.depend1(new D());
        d.depend3(new D());
    }
}

interface interface1{
    public void operation1();
}
interface interface2{
    public void operation2();
}
interface interface3{
    public void operation3();
}
class B implements interface1,interface2{

    public void operation1() {
        System.out.println("B 實現了 operation1");
    }

    public void operation2() {
        System.out.println("B 實現了 operation2");
    }
}
class D implements interface1,interface3{

    public void operation1() {
        System.out.println("D 實現了 operation1");
    }

    public void operation3() {
        System.out.println("D 實現了 operation3");
    }
}

/**
 * A 類 通過接口 interface1 依賴(使用)B 類,但是隻用到 1,2 方法
 */
class A{
    public void depend1(interface1 i){
        i.operation1();
    }
    public void depend2(interface2 i){
        i.operation2();
    }
}
/**
 * C 類 通過接口 interface1 依賴(使用)D 類,但是隻用到 1,3方法
 */
class C{
    public void depend1(interface1 i){
        i.operation1();
    }
    public void depend3(interface3 i){
        i.operation3();
    }
}

三、依賴倒轉原則

  • 高層模塊不應該依賴地層模塊,二者都應該依賴其抽象
  • 抽象不應該依賴細節,細節應該依賴抽象
  • 中心思想:面向接口編程
  • 依賴倒轉原則是基於這樣的設計理念,相對於細節的多變性,抽象的東西要穩定的多。以抽象爲基礎搭建的架構比以細節爲基礎的架構要穩定的多。
  • 在java中,抽象指的是接口或抽象類,細節就是具體的實現類
  • 使用接口或抽象類的目的是制定好規範,而不涉及任何具體的操作,把展現細節的任務交給他們的實現類去完成
  • 代碼實踐
public class Test {
    public static void main(String[] args) {
        Person person = new Person();
        person.receive(new Aemail());
        person.receive(new Awexin());
    }
}
interface Areceiver{
    public String getInfo();
}
class Aemail implements Areceiver{

    @Override
    public String getInfo() {
        return "電子郵件信息:hello world";
    }
}
class Awexin implements Areceiver{

    @Override
    public String getInfo() {
        return "微信信息:hello world";
    }
}
class Person{
    public void receive(Areceiver areceiver){
        System.out.println(areceiver.getInfo());
    }
}

四、里氏替換原則

  • 繼承在給程序設計帶來便利的同時,也帶來了弊端。比如使用繼承會給程序帶來侵入性,程序的可移植性降低,增加對象間的耦合性,如果一個類被其他的類所繼承,則當這個類需要修改時,必須考慮到所有的子類,並且父類修改後,所有涉及到子類的功能都有可能產生故障
  • 在實際編程中,我們常常會通過重寫父類的方法完成新的功能,這樣寫起來雖然簡單,但整個繼承體系的複用性會比較差。特別是運行多態比較頻繁的時候
  • 通用的做法是:原來的父類和子類都繼承-一個更通俗的基類,原有的繼承關係去掉,
    採用依賴,聚合,組合等關係代替.
  • 使用繼承時,遵循里氏替換原則,儘量不要重寫父類中的方法
  • 代碼實踐
/**
 * 不符合里氏替換原則 代碼示例
 */
public class Test {
    public static void main(String[] args) {
        A a = new A();
        System.out.println(a.fun1(7, 3)); // 4
        System.out.println(a.fun1(2, 8)); // -6

        B b = new B();
        System.out.println(b.fun1(7, 3)); // 10
        System.out.println(b.fun1(2, 8)); // 10
        System.out.println(b.fun2(2, 8)); // 19
    }
}

class A {
    public int fun1(int a, int b) {
        return a - b;
    }
}

class B extends A {
    @Override
    public int fun1(int a, int b) {
        return a + b;
    }

    public int fun2(int a, int b) {
        return a + b + 9;
    }
}

/**
 * 使用 組合 代替繼承(使符合里氏替換原則)
 */
class Base {

}

class A extends Base {
    public int fun1(int a, int b) {
        return a - b;
    }
}

class B extends Base {
    // 使用 組合 代替繼承
    private A a = new A();

    public int fun1(int a, int b) {
        return a + b;
    }

    public int fun2(int a, int b) {
        return a + b + 9;
    }

    public int fun3(int a, int b) {
        return this.a.fun1(a, b);
    }
}

五、開閉原則(OCP)

  • 開閉原則(Open Closed Principle)是編程中最基礎、最重要的設計原則
  • 一個軟件實體如類,模塊和函數應該對擴展開放,對修改關閉。用抽象構建框架, .
    用實現擴展細節。
  • 當軟件 需要變化時,儘量通過擴展軟件實體的行爲來實現變化,而不是通過修改已
    有的代碼來實現變化。
  • 編程中遵循其它原則,以及使用設計模式的目的就是遵循開閉原則。
  • 代碼實踐
public class Test {
    public static void main(String[] args) {
        DrawShape draw = new DrawShape();
        draw.drawShape(new Circle());
        draw.drawShape(new Triangle());
    }
}
class DrawShape{
    public void drawShape(Shape shape){
        shape.draw();
    }
}
abstract class Shape{
    public abstract void draw();
}
class Circle extends Shape{

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

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

六、迪米特法則

  • 一個對象應該對其他對象保持最少的瞭解
  • 類與類關係越密切,耦合度越大
  • 迪米特法則,又叫最少知道原則,即一個類對自己依賴的類知道的越少越好。也就是說,對於被依賴的類不管多麼複雜,都儘量將邏輯封裝在類的內.部。對外除了提供的public方法,不對外泄露任何信息
  • 代碼實踐
/**
 * 不符合迪米特法則的代碼示例
 */
public class Test {
    public static void main(String[] args) {
        SchoolManage schoolManage = new SchoolManage();
        schoolManage.printEmployee(new CollegeManage());
    }
}

class SchoolManage {
    private List<Employee> employeeList;

    SchoolManage() {
        employeeList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            employeeList.add(new Employee("學校員工"+i));
        }
    }

    public void printEmployee(CollegeManage collegeManage){
        for(Employee e : this.employeeList){
            System.out.println(e.getName());
        }
        System.out.println("---------------------");
        for(Employee e : collegeManage.getEmployeeList()){
            System.out.println(e.getName());
        }
    }
}

class CollegeManage {
    private List<Employee> employeeList;
    CollegeManage() {
        employeeList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            employeeList.add(new Employee("學院員工"+i));
        }
    }

    public List<Employee> getEmployeeList() {
        return employeeList;
    }
}

class Employee {
    private String name;

    public String getName() {
        return name;
    }

    Employee(String name) {
        this.name = name;
    }
}

/**
 * 將上面的代碼簡單修改一下,使符合迪米特法則
 */
class SchoolManage {
    private List<Employee> employeeList;
    SchoolManage() {
        employeeList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            employeeList.add(new Employee("學校員工"+i));
        }
    }
    public void printEmployee(CollegeManage collegeManage){
        for(Employee e : this.employeeList){
            System.out.println(e.getName());
        }
        System.out.println("--------------------");
        collegeManage.printEmployee();
    }
}

class CollegeManage {
    private List<Employee> employeeList;
    CollegeManage() {
        employeeList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            employeeList.add(new Employee("學院員工"+i));
        }
    }
    public List<Employee> getEmployeeList() {
        return employeeList;
    }
    public void printEmployee(){
        for(Employee e : this.employeeList){
            System.out.println(e.getName());
        }
    }
}

七、合成複用原則

  • 儘量使用 合成 / 聚合 的方式,而不是使用繼承

依賴關係

  • 1、泛化關係:繼承關係
class A{
    
}
class B extends A{
   
}

  • 2、實現關係:類實現接口
interface A{

}
class B implements A{

}
  • 3、關聯關係
    • 單向一對一關係
    • 雙向一對一關係
/**
 * 單向一對一關係
 */
class A{
    private B b;
}
class B implements A{

}
/**
 * 雙向一對一關係
 */
class A{
    private B b;
}
class B implements A{
    private A a;
}

  • 4、聚合關係:表示的是整體和部分的關係,整體與部分可以分開。聚合關係是關聯關係的特例

  • 5、組合關係:組合關係:也是整體與部分的關係,但是整體與部分不可以分開。

class A{
    public String say(){
        return "我是 A ";
    }
}
class B{
    private A a = new A();
    public void func(){
        System.out.println(this.a.say());
    }
}

設計原則核心思想

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

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章