设计模式的七大原则

一、设计模式的目的

  设计模式主要是为了解决在编写代码过程中,面临的耦合性、内聚性、可维护性、可扩展行、重用性、灵活性等多方面的挑战。

  1. 代码重用性:相同功能的代码不用多次编写
  2. 可读性:编程规范,便于他人的阅读和理解
  3. 可扩展性:当需要添加新功能时,非常的方便
  4. 可靠性:当增加新的功能后,对原来的功能没有影响
  5. 最终达到高内聚低耦合的特性

二、设计模式七大原则

  设计模式原则,其实就是程序员在编程时,应当遵守的原则,也是各种设计模式的基础。

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

三、单一职责原则

1,基本介绍

  对类来说的,即一个类应该只负责一项职责。如类A负责两个不同职责:职责1,职责2。当职责1需求变更而改变A时,可能造成职责2执行错误,所以需要将类A的粒度分解为A1,A2

2,应用实例

a)方案1

/**
 * 方案1:违反单一职责,所有的交通工具采用同一种方式运行
 */
public class SingleResponsibility1 {
    public static void main(String[] args) {
        Vehicle vehicle = new Vehicle();
        vehicle.run("摩托车");
        vehicle.run("汽车");
        vehicle.run("飞机");
    }
}

class Vehicle{
    public void run(String vehicle) {
        System.out.println(vehicle + " 在公路上运行....");
    }
}

b)方案2

/**
 * 方案2的分析
 * 1. 遵守单一职责原则
 * 2. 但是这样做的改动很大,即将类分解,同时修改客户端
 * 3. 改进:直接修改Vehicle 类,改动的代码会比较少=>方案3
 */
public class SingleResponsibility2 {
    public static void main(String[] args) {
        RoadVehicle roadVehicle = new RoadVehicle();
        roadVehicle.run("摩托车");
        roadVehicle.run("汽车");

        AirVehicle airVehicle = new AirVehicle();
        airVehicle.run("飞机");
    }
}

class RoadVehicle {
    public void run(String vehicle) {
        System.out.println(vehicle + " 公路运行");
    }
}

class AirVehicle {
    public void run(String vehicle) {
        System.out.println(vehicle + " 天空运行");
    }
}

c)方案3

/**
 * 方式3的分析
 * 1. 这种修改方法没有对原来的类做大的修改,只是增加方法
 * 2. 这里虽然没有在类这个级别上遵守单一职责原则,但是在方法级别上,仍然是遵守单一职责
 */
public class SingleResponsibility3 {
    public static void main(String[] args) {
        Vehicle2 vehicle2  = new Vehicle2();
        vehicle2.run("汽车");
        vehicle2.runWater("轮船");
        vehicle2.runAir("飞机");
    }
}

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 + " 在水中行....");
    }

}

3,注意事项

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

四、接口隔离原则

1,基本介绍

  客户端不应该依赖它不需要的接口,即一个类对另一个类的依赖应该建立在最小的接口上

2,应用案例

  类A通过接口Interface1依赖类B,类C通过接口Interface1依赖类D。但是类A只需要操作类B中的operation1、operation2和operation3,同时类C也只需要操作类D中的operation1、operation4和operation5,但是由于类B和类D都是接口Interface1的实现类,故而都重写了不需要的方法。

  

 源码:基本案例

public interface Interface1 {
    void operation1();

    void operation2();

    void operation3();

    void operation4();

    void operation5();
}

public abstract class A {
    public void dependecy1(Interface1 interface1) {
        interface1.operation1();
    }
    public void dependecy2(Interface1 interface1) {
        interface1.operation2();
    }
    public void dependecy3(Interface1 interface1) {
        interface1.operation3();
    }
}

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 C {
    public void dependecy1(Interface1 interface1) {
        interface1.operation1();
    }
    public void dependecy4(Interface1 interface1) {
        interface1.operation4();
    }
    public void dependecy5(Interface1 interface1) {
        interface1.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");
    }
}
View Code

3,基于接口隔离原则的改进

  将接口Interface1拆分为独立的几个接口,类A和类C分别与他们需要的接口建立依赖关系,即采用接口隔离原则。

  

源码:接口隔离实现

public interface Interface1 {
    void operation1();
}

public interface Interface2 {
    void operation2();

    void operation3();
}

public interface Interface3 {
    void operation4();

    void operation5();
}

public class A {
    public void dependecy1(Interface1 interface1) {
        interface1.operation1();
    }

    public void dependecy2(Interface2 interface2) {
        interface2.operation2();
    }

    public void dependecy3(Interface2 interface2) {
        interface2.operation3();
    }
}

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 C {
    public void dependecy1(Interface1 interface1) {
        interface1.operation1();
    }

    public void dependecy4(Interface3 interface3) {
        interface3.operation4();
    }

    public void dependecy5(Interface3 interface3) {
        interface3.operation5();
    }
}

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");
    }
}
View Code

五、依赖倒转原则

1,基本介绍

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

2,应用案例

a)方案1

/**
 * 方案1:完成Person接受消息的功能
 *  简单易懂
 *  如果我们获取的对象是 微信、短信等,则新增类,同时Person也要增加对应的接收方法
 */
public class Person {
    public void receive(Email email){
        System.out.println(email.getInfo());
    }
}

class Email{
    public String getInfo() {
        return "电子邮件信息:hello word";
    }
}

b)方案2改进

/**
 * 方案2:依赖倒置原则
 *  引入一个抽象的接口IReceiver接口,让不同的接收消息方法都实现这个接口重写getInfo方法
 *  由调用方决定传入的具体对象
 */
public class Person {
    public void receive(IReceiver receiver) {
        System.out.println(receiver.getInfo());
    }
}

interface IReceiver{
    public String getInfo();
}

class Email implements IReceiver{
    @Override
    public String getInfo() {
        return "电子邮件信息:hello word";
    }
}

class WeiXin implements IReceiver {
    @Override
    public String getInfo() {
        return "微信信息:hello wechat";
    }
}

3,依赖关系传递的三种方式(同Spring DI)

a)接口传递

/**
 * 接口传递的方式,将接口ITV传递open方法
 */
class OPenAndClose implements IOPenAndClose {
    @Override
    public void open(ITV itv) {
        itv.play();
    }
}

interface IOPenAndClose {
    public void open(ITV itv);
}

interface ITV {
    public void play();
}
View Code

b)构造方法传递

//方式二:构造方法传递
interface IOpenAndClose {
    public void open();//抽象方法
}

interface ITV {//ITV接口

    public void play();
}

class OpenAndClose implements IOpenAndClose {
    public ITV tv;//成员

    public OpenAndClose(ITV tv) {//构造方法
        this.tv = tv;
    }

    @Override
    public void open() {
        this.tv.play();
    }
}
View Code

c)setter传递

//方式三:setter方法传递
interface IOpenAndClose {
    public void open();//抽象方法
}

interface ITV {//ITV接口

    public void play();
}

class OpenAndClose implements IOpenAndClose {
    private ITV tv;

    public void setTv(ITV tv) {
        this.tv = tv;
    }

    @Override
    public void open() {
        this.tv.play();
    }
}
View Code

4,注意事项和细节

  • 低层模块尽量都要有抽象类和接口,或者两者都有,提高程序的稳定性
  • 变量的声明类型尽量时抽象类或接口,这样我们的变量引用和实际对象间就存在一个缓冲层,利于程序扩展和优化
  • 继承时遵循里氏替换原则

六、里氏替换原则

1,OO中继承性的思考和说明

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

2,基本介绍

  • 如果对每一个类型为T1的对象o1,都有类型为T2的对象o2,使得以T1定义的所有程序P在所有的对象o1都代换成o2时,程序P的行为没有发生变化,那么类型T2是类型T1的子类型。
  • 所有引用基类的地方必须能透明地使用其子类的对象。
  • 在使用继承时,遵循里氏替换原则,在子类中尽量不要重写父类的方法
  • 继承实际上让两个类的耦合性增强了,在适当的情况下,可以通过聚合、组合、依赖来处理

3,应用案例

a)方案1

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

/**
 * 类B继承A
 *  由于B无意识重写了A的fuc1方法,导致最终调用时发现预期类A的fuc1不生效
 */
class B extends A {
    public int fuc1(int a, int b) {
        return a + b;
    }

    public int fuc2(int a, int b) {
        return a * b;
    }
}

b)方案2改进

//定义基类
public class Base {
}

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

/**
 * 类A和类B继承Base类
 *  B使用组合的方式使用A,这样fuc3仍然是类A的方法
 */
class B extends Base {
    A a = new A();
    //这里,重写了 A 类的方法,  可能是无意识
    public int fuc1(int a, int b) {
        return a + b;
    }

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

    //我们仍然想使用 A 的方法
    public int fuc3(int a, int b) {
        return this.a.fuc1(a, b);
    }
}

七、开闭原则

1,基本介绍

  • 开闭原则是编程中最基础、最重要的设计原则
  • 一个软件实体如类、模块和函数应该对扩展开发(指对提供方开放),对修改关闭(指对使用方关闭)。用抽象构建框架,用实现扩展细节
  • 当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。(尽量增加一种功能/扩展,而不是修改这部分可能正在使用的功能)
  • 编程中遵循其他原则,以及使用设计模式的目的就是遵循开闭原则

2,应用案例

a)方案1

public class OCP {

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

}
//绘图的类,使用方
class GraphicEditor{
    //根据不同的type绘制不同的图
    public void drawShape(Shape s) {
        if (s.type == 1) {
            drawRectangle(s);
        } else if (s.type == 2) {
            drawRectangle(s);
        }
    }

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

//基类
abstract class Shape{
    int type;
}

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

class Circle extends Shape {
    public Circle() {
        super.type = 2;
    }
}

问题:该方案违反了设计模式的开闭原则,当需要增加一个图形种类(例:三角形),不仅需要新建类,而且使用方代码也需要添加适配

b)方案2改进

public class OCP {
    public static void main(String[] args) {
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.draw(new Rectangle());
        graphicEditor.draw(new Circle());
    }
}

class GraphicEditor{
    public void draw(Shape s) {
        s.draw();
    }
}

abstract class Shape{
    public abstract void draw();
}

class Rectangle extends Shape {

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

class Circle extends Shape {

    @Override
    public void draw() {
        System.out.println("绘制圆形");
    }
}

八、迪米特法则

1,基本介绍

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

2,应用实例

  有一个学校,下属有各个学院和总部,现要求打印出学校总部员工 ID 和学院员工的 id

a)方案1

public class Demeter {
    public static void main(String[] args) {
        SchoolManage manage = new SchoolManage();
        manage.printAllEmp(new CollegeManage());
    }
}

//学校总部员工
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 CollegeManage {

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

//学校总部管理
class SchoolManage {
    public List<Employee> getAllEmployee() {
        List<Employee> list = new ArrayList<Employee>();
        for (int i = 0; i < 10; i++) {
            Employee emp = new Employee();
            emp.setId("学校总部员工 id= " + i);
            list.add(emp);
        }
        return list;
    }

    //这里的  CollegeEmployee 不是    SchoolManager 的直接朋友
    //违反了迪米特法则
    public void printAllEmp(CollegeManage collegeManage) {
        List<CollegeEmployee> allEmployee = collegeManage.getAllEmployee();
        System.out.println("------------学院员工------------");
        for (CollegeEmployee e : allEmployee) {
            System.out.println(e.getId());
        }
        //获取到学校总部员工
        List<Employee> list2 = this.getAllEmployee();
        System.out.println("------------学校总部员工------------");
        for (Employee e : list2) {
            System.out.println(e.getId());
        }

    }
}

问题:由于在SchoolManage中,CollegeEmployee类并不是SchoolManage类的直接朋友。按照迪米特法则,应该避免类中出现这样非直接朋友关系的耦合

b)方案2

优化:完整代码

//学院管理
class CollegeManage {

    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 printCollegeEmp() {
        List<CollegeEmployee> allEmployee = this.getAllEmployee();
        System.out.println("------------学院员工------------");
        for (CollegeEmployee e : allEmployee) {
            System.out.println(e.getId());
        }
    }
}

//学校总部管理
class SchoolManage {
    public List<Employee> getAllEmployee() {
        List<Employee> list = new ArrayList<Employee>();
        for (int i = 0; i < 10; i++) {
            Employee emp = new Employee();
            emp.setId("学校总部员工 id= " + i);
            list.add(emp);
        }
        return list;
    }

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

    }
}

3,注意事项

  • 迪米特法则的核心是降低类之间的耦合
  • 由于每个类都减少了不必要的依赖,因此迪米特法则只是要求降低类间(对象间)耦合关系,并不是要求完全没有依赖关系

九、合成复用原则

1,定义

  • 合成复用原则是指尽量使用对象组合/聚合,而不是继承关系达到软件复用的目的。可以说使系统更加灵活,降低类与类之间的耦合度,一个类的变化对其他类造成的影响相对较少。
  • 继承我们叫做白箱复用,相当于把所有的实现细节暴露给子类。组合/聚合也称之为黑箱复用,对类以外的对象是无法获取到实现细节的。要根据具体的业务场景来做代码设计,其实也都要遵循OOP模型

十、 设计原则核心思想

  • 1)找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起。
  • 2)针对接口编程,而不是针对实现编程。
  • 3)为了交互对象之间的松耦合设计而努力
posted @ 2021-08-21 20:31  MXC肖某某  阅读(610)  评论(0编辑  收藏  举报