设计模式-七大原则(下篇)

2.4 里氏替换原则

2.4.1 基本介绍

  • 所有引用基类的地方必须能透明地使用其子类的对象
  • 使用继承时,遵循里氏替换原则,在子类中尽量不要重写父类的方法
  • 继承实际上让两个类耦合性(比如B和C继承了父类A,此时A进行了修改会影响到B和C)增强了,在适当的情况下可以通过聚合,组合,依赖来解决问题

2.4.2 应用实例

未遵循里氏替换原则:

public static void main(String[] args) {
        A a = new A();
        System.out.println("11-3=" + a.func1(11, 3));
        B b = new B();
        System.out.println("11-3=" + b.func1(11, 3));  // 本意是求出11-3,结果输出14
}
class A {
    public int func1(int num1, int num2) {
        return num1 - num2;
    }
}
class B extends A {
    //这里不小心重写了A类的方法(但还是认为功能是两数相减)
    public int func1(int a, int b) {
        return a + b;
    }
}

遵循里氏替换原则:

public static void main(String[] args) {
        A a = new A();
        System.out.println("11-3=" + a.func1(11, 3));
        B b = new B();
        // 因为B类不再继承A类,调用完成的功能就会很明确(对于同名的函数不会在联想到是重写父类的方法)
        System.out.println("11+3=" + b.func1(11, 3));
        // 使用组合仍然可以使用到A类相关方法
        System.out.println("11-3=" + b.func2(11, 3));
}
//创建一个更加基础的基类
class Base {
    //把更加基础的方法和成员写到Base类
}
class A extends Base {
    // 返回两个数的差
    public int func1(int num1, int num2) {
        return num1 - num2;
    }
}
class B extends Base {
    // 如果B需要使用A类的方法,使用组合关系
    private A a = new A();

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

    public int func2(int a, int b) {
        return this.a.func1(a, b);
    }
}

2.5 开闭原则

2.5.1 基本介绍

  • 编程中最基础、最重要的设计原则
  • 软件实体如类,模块和函数应该对扩展开放(即对提供功能方开放),对修改关闭(即对使用功能方关闭)
  • 当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码
  • 遵循其它原则以及使用设计模式的目的就是遵循开闭原则

2.5.2 应用实例

未遵循开闭原则

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());
    }
}

// 方法1的优缺点:
//  1.易理解和操作
//  2.但是违法Ocp原则,新增一个图形类别时修改代码较多(使用方GraphicEditor共新增两处代码)

// 用于绘图的类 [使用方]
class GraphicEditor {
    // 传入普通类Shape,根据type来绘制不同的图形
    public void drawShape(Shape s) {
        if (s.m_type == 1)
            drawRectangle(s);
        else if (s.m_type == 2)
            drawCircle(s);
            // 新增代码块
        else if (s.m_type == 3)
            drawTriangle(s);
    }

    // 绘制矩形
    public void drawRectangle(Shape r) {
        System.out.println(" 绘制矩形 ");
    }

    // 绘制圆形
    public void drawCircle(Shape r) {
        System.out.println(" 绘制圆形 ");
    }

    // 新增代码块②
    // 绘制三角形
    public void drawTriangle(Shape r) {
        System.out.println(" 绘制三角形 ");
    }
}
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;
    }
}

遵循开闭原则

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());
    }
}

// 解决方法:把Shape类做成抽象类,并提供抽象方法draw,让子类去实现
// 优点:使用方GraphicEditor的代码无需修改

// 用于绘图的类 [使用方]
class GraphicEditor {
    // 传入抽象类Shape,调用draw方法
    public void drawShape(Shape s) {
        s.draw();
    }
}

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.6 迪米特原则

2.6.1 基本介绍

  • 一个对象应该对其他对象保持最少的了解
  • 类与类关系越密切,耦合度越大
  • 该原则称为最少知道原则,即一个类对自己依赖的类知道的越少越好
  • 只与直接的朋友通信,非直接朋友最好不要以局部变量的形式出现在类的内部(比如在A类某个方法中直接new一个B类对象):
    • 朋友:两个对象之间有耦合关系
    • 直接朋友:类中出现成员变量或类中某个方法的参数/返回值中的类

2.6.2 应用实例

未遵循迪米特原则

public class Demeter {

    public static void main(String[] args) {
        //创建了一个 SchoolManager 对象
        SchoolManager schoolManager = new SchoolManager();
        //输出学院的员工id 和  学校总部的员工信息
        schoolManager.printAllEmployee(new CollegeManager());

    }

}

// 学校总部员工类
class Employee {
    private String id;

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

    public String getId() {
        return id;
    }
}

// 学院的员工类
class CollegeEmployee {
    private String id;

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

    public String getId() {
        return id;
    }
}

// 管理学院员工的管理类
class CollegeManager {
    // 返回学院的所有员工
    public List<CollegeEmployee> getAllEmployee() {
        List<CollegeEmployee> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            CollegeEmployee emp = new CollegeEmployee();
            emp.setId("学院员工id= " + i);
            list.add(emp);
        }
        return list;
    }
}

// 学校管理类
// SchoolManager类的直接朋友类:
//  ① getAllEmployee方法中的返回值Employee类
//  ② printAllEmployee方法中的参数CollegeManager
// 但是printAllEmployee方法中的局部变量CollegeEmployee不是直接朋友,违背了迪米特法则
class SchoolManager {
    // 返回学校总部的员工
    public List<Employee> getAllEmployee() {
        List<Employee> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Employee emp = new Employee();
            emp.setId("学校总部员工id= " + i);
            list.add(emp);
        }
        return list;
    }

    // 完成输出学校总部和学院员工信息(id)
    void printAllEmployee(CollegeManager sub) {

        // 获取到学院员工
        List<CollegeEmployee> list1 = sub.getAllEmployee();
        System.out.println("------------学院员工------------");
        for (CollegeEmployee e : list1) {
            System.out.println(e.getId());
        }
        // 获取到学校总部员工
        List<Employee> list2 = this.getAllEmployee();
        System.out.println("------------学校总部员工------------");
        for (Employee e : list2) {
            System.out.println(e.getId());
        }
    }
}

遵循迪米特原则

public class Demeter {
    public static void main(String[] args) {
        SchoolManager schoolManager = new SchoolManager();
        // 输出学院的员工id和学校总部的员工信息
        schoolManager.printAllEmployee(new CollegeManager());
    }
}

// 解决方法:将输出学院的员工方法封装到CollegeManager(之前相当于在别人的方法中输出自己的信息)
// 注意:由于CollegeEmployee类已经是CollegeManager的直接朋友(因为是getAllEmployee方法的返回值),
//      尽管它出现在printEmployee方法的局部变量中也不违法迪米特原则

// 学校总部员工类
class Employee {
    private String id;

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

    public String getId() {
        return id;
    }
}

// 学院的员工类
class CollegeEmployee {
    private String id;

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

    public String getId() {
        return id;
    }
}

// 管理学院员工的管理类
class CollegeManager {
    // 返回学院的所有员工
    public List<CollegeEmployee> getAllEmployee() {
        List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
        for (int i = 0; i < 10; i++) {
            CollegeEmployee emp = new CollegeEmployee();
            emp.setId("学院员工id= " + i);
            list.add(emp);
        }
        return list;
    }

    // 输出学院员工的信息
    public void printEmployee() {
        //获取到学院员工
        List<CollegeEmployee> list1 = getAllEmployee();
        System.out.println("------------学院员工------------");
        for (CollegeEmployee e : list1) {
            System.out.println(e.getId());
        }
    }
}

//学校管理类
class SchoolManager {
    // 返回学校总部的员工
    public List<Employee> getAllEmployee() {
        List<Employee> list = new ArrayList<Employee>();

        for (int i = 0; i < 5; i++) {
            Employee emp = new Employee();
            emp.setId("学校总部员工id= " + i);
            list.add(emp);
        }
        return list;
    }

    // 输出学校总部和学院员工信息(id)
    void printAllEmployee(CollegeManager sub) {

        sub.printEmployee();

        // 获取到学校总部员工
        List<Employee> list2 = this.getAllEmployee();
        System.out.println("------------学校总部员工------------");
        for (Employee e : list2) {
            System.out.println(e.getId());
        }
    }
}

2.6.3 注意事项和细节

  • 迪米特法则的核心是降低类之间的耦合,并不是要求完全没有依赖关系

2.7 合成复用原则

2.7.1 基本介绍

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

2.7.2 应用实例

假设A类有三个方法operation1、operation2、operation3,此时B类要使用operation1方法,如果让B去继承A,则两个类之间耦合性过强,如图中①部分所示:

在这里插入图片描述

为了降低耦合性,可以改为图中的②(依赖关系)、③(组合关系)、④(聚合关系)

3.设计原则的核心

  • 将应用中可能需要变化之处独立出来
  • 针对接口编程
  • 为了交互对象之间的松耦合设计而努力

4.参考

https://www.bilibili.com/video/BV1G4411c7N4?p=14-22

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值