【设计模式7大原则详解】

设计模式的目的

编写软件过程种,面临着来着耦合性,内聚性,以及可维护性,可扩展性,重用性,灵活性等多方便的挑战,设计模式是为了让程序具有一下特点

  1. 代码重用性
  2. 代码可读性
  3. 可扩展性
  4. 可靠性
  5. 使得程序高内聚,低耦合的特点

设计模式七大原则

设计模式原则,其实就是程序员在编程时,应当遵守的原则,也是各种设计模式的基础(即:设计模式为什么这样设计的依据)
常用的七大原则有:

  1. 单一职则原则
  2. 接口隔离原则
  3. 依赖倒置原则
  4. 里式替换原则
  5. 开闭原则
  6. 迪米特法则
  7. 合成复用原则

1. 单职责原则

基本介绍

对类来说的,即一个类应该只负责一项职则。如新增和编辑功能,使用同一个类作为输入,当新增类的需求变更导致 增加或者减少字段,编辑功能可能导致执行错误。

注意事项和使用细节

  1. 降低类的复杂度,一个类只负责一项职则。
  2. 提高类的可读性,可维护性
  3. 降低变更引起的风险
  4. 通常情况下,我们应当遵守单以职责原则,只有逻辑足够简单,才可以在代码级违反单一职则原则;只有类中的方法数量足够少,可以在方法级别保持单一职则原则。

2.接口隔离原则

基本介绍

客户端不应该依赖它不需要的接口,即一个类对另一个类的依赖应该建立在最小的接口上
观察这张图:
【设计模式7大原则详解】_第1张图片
类A通过接口Interface1依赖B,类C通过接口Interface1依赖类D,如果接口interface1对类A和类C来说都不是最小接口,那么类B和类D都必须实现他们不需要的方法。
代码实现如下

public interface Interface1 {

    void operation1();
    void operation2();
    void operation3();
    void operation4();
    void operation5();
}
public 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");
    }
}

public 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");
    }
}
public class A {  //A类通过接口 Interface1 依赖B类,但是指挥用到123方法

    public void depend1(Interface1 i){
        i.operation1();
    }

    public void depend2(Interface1 i){
        i.operation2();
    }
    public void depend3(Interface1 i){
        i.operation3();
    }
}
public class C {//A类通过接口 Interface1 依赖B类,但是指挥用到145方法
    public void depend1(Interface1 i){
        i.operation1();
    }
    public void depend2(Interface1 i){
        i.operation4();
    }
    public void depend3(Interface1 i){
        i.operation5();
    }
}

按照隔离原则应当这样处理:
将接口interface1拆分成为独立的几个接口(我们拆成三个),类A和类C分别与他们需要的接口建立依赖关系。也就是采用接口隔离原则。

应用实例

【设计模式7大原则详解】_第2张图片
代码实现

public interface Interface1 {
    void operation1();
}
public interface Interface2 {
    void operation2();
    void operation3();
}
public interface Interface3 {
    void operation4();
    void operation5();
}
public 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");
    }
}
public 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");
    }
}
public class A {  //A类通过接口 Interface1 依赖B类,但是指挥用到123方法
    public void depend1(Interface1 i){
        i.operation1();
    }
    public void depend2(Interface2 i){
        i.operation2();
    }
    public void depend3(Interface2 i){
        i.operation3();
    }
}
public class C {//A类通过接口 Interface1 依赖B类,但是指挥用到145方法
    public void depend1(Interface1 i){
        i.operation1();
    }
    public void depend2(Interface3 i){
        i.operation4();
    }
    public void depend3(Interface3 i){
        i.operation5();
    }
}

3.依赖倒置原则

基本介绍

依赖倒转原则(Dependence Inversion Principle)是指:

  1. 高层模块不应该依赖底层模块,二者都应依赖其抽象
  2. 抽象不应该依赖细节,细节应该依赖抽象
  3. 依赖倒置的中心思想是面向接口编程
  4. 依赖倒置原则是基于这样的设计理念:相对于细节的多边性,抽象的东西要稳定的多,以抽象为基础搭建的架构比以细节为基础的架构要稳定的多。在JAVA中,抽象指的是接口或抽象类,细节就是具体的实现。
  5. 使用接口或者抽象类的目的是制定好规范,而不设计任何具体的操作,把展现细节的任务交给他们的实现类去完成。

应用实例

比如:完成一个Person类接收消息的功能
例子1:接收邮件消息

public class Email {
    public String getInfo(){
        return "电子邮件信息:Hello world";
    }
}
public 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());
}

思考:如果我们要获取的对象是 微信,短信等等,则新增类,同时Person也要增加对应的方法
解决思路:引入一个抽象的接口IReceiver,表示接收者,这样Person类与接口IReceiver发生依赖,因为Email,WerXin等等属于接收范围,他们各自实现IReceiver接口就OK了,这样就符合依赖倒置原则。
代码如下:

/**
 * @Author:lpj
 * @name:IReceiver
 * @Date:2023/12/13 14:59
 * @describe:定义接口
 */
public interface IReceiver {
    public String getInfo();
}
public class Email implements IReceiver{

    @Override
    public String getInfo() {
        return "电子邮件信息:Hello world";
    }
}
public class WeiXin implements IReceiver{
    @Override
    public String getInfo() {
        return "微信消息:hello,ok";
    }
}
public class Person {
    public void receive(IReceiver receiver){
        System.out.println(receiver.getInfo());
    }
}
public static void main(String[] args) {
    Person person = new Person();
    person.receive(new Email());
    person.receive(new WeiXin());
}

依赖关系传递的三种方式

  1. 接口传递,如上已经实现
  2. 构造方法传递
  3. setter方式传递
    结构构造方法传递代码实现如下: (主要针对Person类做出更改)
public interface IReceiver {
    public String getInfo();
}
public class Email implements IReceiver {
    @Override
    public String getInfo() {
        return "电子邮件信息:Hello world";
    }
}
public class WeiXin implements IReceiver{
    @Override
    public String getInfo() {
        return "微信消息:hello,ok";
    }
}
public class Person {
    private IReceiver receiver;//成员
    public Person(IReceiver receiver){
        this.receiver = receiver;
    }
    public void getMessage(){
        System.out.println(receiver.getInfo());
    }
}
public static void main(String[] args) {
    Person person = new Person(new WeiXin());
    Person person1 = new Person(new Email());
    person.getMessage();
    person1.getMessage();
}

setter方式传递代码实现如下(主要代码也是在Person类)

public class Person {
    private IReceiver receiver;//成员
//    public Person(IReceiver receiver){
//        this.receiver = receiver;
//    }
    public void setReceiver(IReceiver receiver) {
        this.receiver = receiver;
    }
    public void getMessage(){
        System.out.println(receiver.getInfo());
    }
}
public static void main(String[] args) {
    Person person = new Person();
    Person person1 = new Person();
    person.setReceiver(new WeiXin());
    person1.setReceiver(new Email());
    person.getMessage();
    person1.getMessage();
}

注意事项和细节

  1. 底层模块应将都要有抽象类或者接口,或者两者都有,程序稳定性更好。
  2. 变量的声明尽量是抽象类或者接口,这样我们的变量引用和实际对象间就存在一个缓冲层,利于程序扩展和优化
  3. 继承时应遵循里式替换原则

4.里式替换原则

IOO中继承性的思考和说明

  1. 继承包含这样一层含义:父类中凡是已经实现好的方法,实际上是在设定规范和契约,虽然它不强制要求所有的子类必须遵循这些契约,但是如果子类对这些已经实现的方法任意修改,就会对整个继承体系造成破坏。
  2. 继承在给程序设计带来便利的同时,也带来了弊端。比如使用继承会给程序带来侵入性,程序的可移植性降低,增加对象间的耦合性,如果一个类被其他的类所继承,则当这个类需要修改时,必须考虑到所有的子类,并且父类修改之后,所有涉及到的子类的功能都可能产生故障
  3. 问题提出:在编程中,如果正确的使用继承?=>里式替换原则

基本介绍

  1. 里式替换原则(Liskov Substitution Principle)在1988年,由麻省理工学院一位姓里的女士提出的。
  2. 如果对每个类型为T1的对象o1,都有类型为T2的对象o2,使得以T1定义的所有程序P在所有的对象o1都换成o2时,程序P的行为没有发生变化,那么类型T2是类型T1的子类型。换句话说,所有引用基类的方法必须能够透明的使用其子类的对象。(有点绕···)
  3. 在使用继承时,遵循里式替换原则,在子类中尽量不要重写父类的方法。
  4. 继承实际上是让两个类耦合性增强了,在适当的情况下,可以通过聚合,组合,依赖来解决问题。

看个程序,思考下问题和解决思路

public class A {

    public int func1(int num1,int num2){
        return num1-num2;
    }
}
public class B extends A {

    //这里重写了A类的方法,可能是无意识
    public int func1(int a,int b){
        return a+b;
    }

    public int func2(int a,int b){
        return func1(a,b) +9;
    }
}
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();
    System.out.println("11-3=" + b.func1(11,3));
    System.out.println("1-8=" +b.func1(1,8));
    System.out.println("11+3+9=" +b.func2(11,3));
}

运行结果如下:
【设计模式7大原则详解】_第3张图片

解决办法

  1. 我们发现原来运行正常的相减功能发生了错误。原因就是类B无意中重写了父类的方法,造成原有功能出错。在实际编程中,我们常常会通过重写父类的方法来完成新功能,这样写起来简单,但是整个继承体系的复用性就会比较差,特别是运行多态比较频繁的时候。
  2. 通用的做法是:原来的父类和子类都继承一个更通俗的基类,原有的继承关系去掉,采用依赖,聚合,组合等关系去代替。

代码实现:

public class Base {
    //更加基础的方法和成员写道该类
    public int Base;
    public void BaseMethod(){
    }
}

public class A extends Base{

    public int func1(int num1,int num2){
        return num1-num2;
    }
}

public class B extends Base {
    //B使用A类的方法,使用组合关系
    private A a = new A();
    
    //这里重写了A类的方法,可能是无意识
    public int func1(int a,int b){
        return super.Base+a+b;
    }

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

    public int func3(int a,int b){
        return this.a.func1(a,b);
    }
    @Override
    public void BaseMethod() {
        super.BaseMethod();
    }
}

5.开闭原则

基本原则

  1. 开闭原则(Open Closed Principle)是编程中最基础、最重要的设计原则。
  2. 一个软件实体如类,模块和函数应该对扩展开放(对提供方),对修改关闭(对使用方)。用抽象构建框架,用实现扩展细节。
  3. 当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有代码来实现变化。
  4. 编程中遵循其他原则,以及使用设计模式的目的就是遵循开闭原则。

看一段代码

一个画图形的功能
类图设计如下:
【设计模式7大原则详解】_第4张图片

public class Shape { //基类
    public int m_type;
}
public class Rectangle extends Shape {
    Rectangle(){
        super.m_type =1;
    }
}
public class Circle extends Shape {
    Circle(){
        super.m_type = 2;
    }
}
public class Triangle extends Shape{ //新增一个图形
    Triangle(){
        super.m_type = 3;
    }
}
public class GraphicEditor {
    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("绘制三角形");
    }
}
//调用
    public static void main(String[] args) {
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Circle());
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Triangle());
    }

分析一下:

  1. 优点是比较好理解,简单易操作。
  2. 确定就是违反了设计原则OCP原则,即对外开放,对修改关闭,即,我们给类增加新功能的时候,经量不要修改代码,或者尽量可能少修改代码。
  3. 比如我们增加了一个三角形,修改的地方比较多。

改进思路分析

思路:把创建Shape 类做成一个抽象类,并提供一个抽象的draw方法,让子类去实现即可,这样我们有新的图形种类时,只需要让新的图形类继承shape,并实现draw方法,使用方的代码就不用修改,满足了开闭原则。
代码如下:

public abstract class Shape { //基类
    public int m_type;

    public abstract void draw();
}
public class Triangle extends Shape{ //新增一个图形
    Triangle(){
        super.m_type = 3;
    }
    @Override
    public void draw() {
        System.out.println("绘制三角形");
    }
}
public class Rectangle extends Shape {
    Rectangle(){
        super.m_type =1;
    }

    @Override
    public void draw() {
        System.out.println("绘制矩形");
    }
}
public class Circle extends Shape {
    Circle(){
        super.m_type = 2;
    }

    @Override
    public void draw() {
        System.out.println("绘制圆形");
    }
}
public class GraphicEditor {
    public void drawShape(Shape s){
        s.draw();
    }

}
//调用
    public static void main(String[] args) {
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Circle());
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Triangle());
    }

6.迪米特法则

基本介绍

  1. 一个对象应该对其他对象保持最少的了解
  2. 类与类的关系越密切,偶尔度越大
  3. 迪米特法则(Demeter principle)又叫最少知道原则,即一个类对自己依赖的类知道的越少越好。也就是说,被依赖的类不管多么复杂,都尽量将逻辑封装在类的内部,对外除了提供public方法,不对外泄露任何消息
  4. 还有个更简单的定义:只与直接的朋友通信
  5. 直接的朋友:每个对象都会与其他对象有耦合关系,只要两个对象之间有耦合关系,我们就说这两个对象之间时朋友关系,耦合的关系很多,依赖,关联,组合,聚合,等。其中,我们称出现的成员变量,方法参数,方法返回值中的类为直接的朋友,而出现在局部变量中的类不是直接的朋友,也就是陌生的类最好不要以局部变量形式出现在类的内部。

应用实例

1.有一个学校,下属有各个学院和总部,现要求打印出学校总部员工ID和学院员工ID
代码实现如下:

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

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}
public class Employee { //总部员工类
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}
public class CollegeManager { //管理学院员工的管理类

    public List<CollegeEmployee> getAllEmployee(){
        List<CollegeEmployee> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            CollegeEmployee employee = new CollegeEmployee();
            employee.setId("学院员工id:"+i);
            list.add(employee);
        }
        return list;
    }
}
public class SchoolManager {
    public List<Employee> getAllEmployee(){
        List<Employee> list = new ArrayList<>();

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

    //该方法完成输出学院总部和学院员工信息id
    void printAllEmployee(CollegeManager sub){
        //学院员工
        List<CollegeEmployee> list1 = sub.getAllEmployee();

        for (CollegeEmployee e :list1){
            System.out.println(e.getId());
        }
        //学校总部员工
        List<Employee> list2 = this.getAllEmployee();
        for (Employee e :list2){
            System.out.println(e.getId());
        }
    }
}
//调用
    public static void main(String[] args) {
        SchoolManager schoolManager = new SchoolManager();
        schoolManager.printAllEmployee(new CollegeManager());
    }

问题分析:

  1. CollegeEmployee 不是SchoolManager的直接朋友
  2. CollegeEmployee是以局部变量方式出现在 SchoolManager
  3. 违反了迪米特法则

代码改进

主要把SchoolManager 类中 CollegeManager 的具体实现剥离开,在它自己类中实现,在SchoolManager中调用方法即可。

public class CollegeManager { //管理学院员工的管理类

    public List<CollegeEmployee> getAllEmployee(){
        List<CollegeEmployee> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            CollegeEmployee employee = new CollegeEmployee();
            employee.setId("学院员工id:"+i);
            list.add(employee);
        }
        return list;
    }

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

public class SchoolManager {
    public List<Employee> getAllEmployee(){
        List<Employee> list = new ArrayList<>();

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

    //该方法完成输出学院总部和学院员工信息id
    void printAllEmployee(CollegeManager sub){
        //学院员工
        sub.printEmployee();
        //学校总部员工
        List<Employee> list2 = this.getAllEmployee();
        for (Employee e :list2){
            System.out.println(e.getId());
        }
    }
}

注意事项和细节

  1. 迪米特法则的核心是降低类之间的耦合
  2. 但是注意,由于每个类都减少了不必要的依赖,因此迪米特法则只是要求降低类间的耦合关系,并不是完全没有依赖关系。

7.合成复用原则

基本介绍

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

核心思想

  1. 找出应用中可能的变化之处,把他们独立出来,不要和那些不需要变化的代码混在一起
  2. 针对接口编程,而不是正对实现编程
  3. 为了交互对象之间的松耦合设计而努力

你可能感兴趣的:(JAVA,设计模式,设计模式,java)