设计模式七大原则

「爱情、让人受尽委屈。」 2022-12-29 06:54 270阅读 0赞

#

  • 设计模式七大原则
    • 一、设计模式的目的
    • 二、设计模式七大原则
      • 1、单一职责原则
      • 2、接口隔离原则(Interface Segregation Principle)
      • 3、依赖倒转原则
      • 4、里氏替换原则
      • 5、开闭原则
      • 6、迪米特法则
      • 7、合成复用原则(Composite Reuse Principle)
    • 三、设计原则核心思想

设计模式七大原则

一、设计模式的目的

编写软件过程中,程序员面临着来自 耦合性,内聚性以及可维护性,可扩展性,重用性,灵活性 等多方面的挑战,设计模式是为了让程序(软件),具有更好

  1. 代码重用性 (即:相同功能的代码,不用多次编写)
  2. 可读性 (即:编程规范性, 便于其他程序员的阅读和理解)
  3. 可扩展性 (即:当需要增加新的功能时,非常的方便,称为可维护)
  4. 可靠性 (即:当我们增加新的功能后,对原来的功能没有影响)
  5. 使程序呈现高内聚,低耦合的特性

二、设计模式七大原则

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

设计模式常用的七大原则有:

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

1、单一职责原则

基本介绍

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

应用实例

以交通工具案例讲解

方案1:

  1. package principle.singleresponsibility;
  2. public class SingleResponsibility1 {
  3. public static void main(String[] args) {
  4. Vehicle vehicle = new Vehicle();
  5. vehicle.run("摩托车");
  6. vehicle.run("汽车");
  7. vehicle.run("飞机");
  8. }
  9. }
  10. // 交通工具类
  11. // 方 式 1
  12. // 1. 在方式 1 的 run 方法中,违反了单一职责原则
  13. // 2. 解决的方案非常的简单,根据交通工具运行方法不同,分解成不同类即可
  14. class Vehicle {
  15. public void run(String vehicle) {
  16. System.out.println(vehicle + " 在公路上运行....");
  17. }
  18. }

方案2:

  1. package principle.singleresponsibility;
  2. public class SingleResponsibility2 {
  3. public static void main(String[] args) {
  4. RoadVehicle roadVehicle = new RoadVehicle();
  5. roadVehicle.run("摩托车");
  6. roadVehicle.run("汽车");
  7. AirVehicle airVehicle = new AirVehicle();
  8. airVehicle.run("飞机");
  9. }
  10. }
  11. //方案 2 的分析
  12. //1. 遵守单一职责原则
  13. //2. 但是这样做的改动很大,即将类分解,同时修改客户端
  14. //3. 改进:直接修改 Vehicle 类,改动的代码会比较少=>方案 3
  15. class RoadVehicle {
  16. public void run(String vehicle) {
  17. System.out.println(vehicle + "公路运行");
  18. }
  19. }
  20. class AirVehicle {
  21. public void run(String vehicle) {
  22. System.out.println(vehicle + "天空运行");
  23. }
  24. }
  25. class WaterVehicle {
  26. public void run(String vehicle) {
  27. System.out.println(vehicle + "水中运行");
  28. }`
  29. }

方案3:

  1. package principle.singleresponsibility;
  2. public class SingleResponsibility3 {
  3. public static void main(String[] args) {
  4. Vehicle2 vehicle2 = new Vehicle2();
  5. vehicle2.run("汽车");
  6. vehicle2.runWater("轮船");
  7. vehicle2.runAir("飞机");
  8. }
  9. }
  10. //1. 这种修改方法没有对原来的类做大的修改,只是增加方法
  11. //2. 这里虽然没有在类这个级别上遵守单一职责原则,但是在方法级别上,仍然是遵守单一职责
  12. class Vehicle2 {
  13. public void run(String vehicle) {
  14. //处理
  15. System.out.println(vehicle + " 在公路上运行....");
  16. }
  17. public void runAir(String vehicle) {
  18. System.out.println(vehicle + " 在天空上运行....");
  19. }
  20. public void runWater(String vehicle) {
  21. System.out.println(vehicle + " 在水中行....");
  22. }
  23. }

单一职责原则注意事项和细节

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

2、接口隔离原则(Interface Segregation Principle)

基本介绍

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

2、先看一张图:
在这里插入图片描述

  • 类 A 通过接口 Interface1 依赖类 B,类 C 通过接口 Interface1 依赖类 D,如果接口 Interface1 对于类 A 和类 C 来说不是最小接口,那么类 B 和类 D 必须去实现他们不需要的方法。
  • 按隔离原则应当这样处理:
    将接口 Interface1 拆分为独立的几个接口(这里我们拆分成 3 个接口),类 A 和类 C 分别与他们需要的接口建立依赖关系。也就是采用接口隔离原则。

应用实例

1、类 A 通过接口 Interface1 依赖类 B,类 C 通过接口 Interface1 依赖类 D,请编写代码完成此应用实例。

2、没有使用接口隔离原则代码

  1. package principle.segregation;
  2. public class Segregation1 {
  3. public static void main(String[] args) {
  4. }
  5. }
  6. //接口
  7. interface Interface1 {
  8. void operation1();
  9. void operation2();
  10. void operation3();
  11. void operation4();
  12. void operation5();
  13. }
  14. class B implements Interface1 {
  15. public void operation1() {
  16. System.out.println("B 实现了 operation1");
  17. }
  18. public void operation2() {
  19. System.out.println("B 实现了 operation2");
  20. }
  21. public void operation3() {
  22. System.out.println("B 实现了 operation3");
  23. }
  24. public void operation4() {
  25. System.out.println("B 实现了 operation4");
  26. }
  27. public void operation5() {
  28. System.out.println("B 实现了 operation5");
  29. }
  30. }
  31. class D implements Interface1 {
  32. public void operation1() {
  33. System.out.println("D 实现了 operation1");
  34. }
  35. public void operation2() {
  36. System.out.println("D 实现了 operation2");
  37. }
  38. public void operation3() {
  39. System.out.println("D 实现了 operation3");
  40. }
  41. public void operation4() {
  42. System.out.println("D 实现了 operation4");
  43. }
  44. public void operation5() {
  45. System.out.println("D 实现了 operation5");
  46. }
  47. }
  48. class A {
  49. //A 类通过接口 Interface1 依赖(使用) B 类,但是只会用到 1,2,3 方法
  50. public void depend1(Interface1 i) {
  51. i.operation1();
  52. }
  53. public void depend2(Interface1 i) {
  54. i.operation2();
  55. }
  56. public void depend3(Interface1 i) {
  57. i.operation3();
  58. }
  59. }
  60. class C {
  61. //C 类通过接口 Interface1 依赖(使用) D 类,但是只会用到 1,4,5 方法
  62. public void depend1(Interface1 i) {
  63. i.operation1();
  64. }
  65. public void depend4(Interface1 i) {
  66. i.operation4();
  67. }
  68. public void depend5(Interface1 i) {
  69. i.operation5();
  70. }
  71. }

应传统方法的问题和使用接口隔离原则改进

1、类 A 通过接口 Interface1 依赖类 B,类 C 通过接口 Interface1 依赖类 D,如果接口 Interface1 对于类 A 和类 C 来说不是最小接口,那么类 B 和类 D 必须去实现他们不需要的方法。

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

3、接口 Interface1 中出现的方法,根据实际情况拆分为三个接口。

在这里插入图片描述

  1. package principle.segregation.improve;
  2. public class Segregation1 {
  3. public static void main(String[] args) {
  4. // 使用一把
  5. A a = new A();
  6. a.depend1(new B()); // A 类通过接口去依赖 B 类
  7. a.depend2(new B());
  8. a.depend3(new B());
  9. C c = new C();
  10. c.depend1(new D()); // C 类通过接口去依赖(使用)D 类
  11. c.depend4(new D());
  12. c.depend5(new D());
  13. }
  14. }
  15. // 接 口 1
  16. interface Interface1 {
  17. void operation1();
  18. }
  19. // 接 口 2
  20. interface Interface2 {
  21. void operation2();
  22. void operation3();
  23. }
  24. // 接 口 3
  25. interface Interface3 {
  26. void operation4();
  27. void operation5();
  28. }
  29. class B implements Interface1, Interface2 {
  30. public void operation1() {
  31. System.out.println("B 实现了 operation1");
  32. }
  33. public void operation2() {
  34. System.out.println("B 实现了 operation2");
  35. }
  36. public void operation3() {
  37. System.out.println("B 实现了 operation3");
  38. }
  39. }
  40. class D implements Interface1, Interface3 {
  41. public void operation1() {
  42. System.out.println("D 实现了 operation1");
  43. }
  44. public void operation4() {
  45. System.out.println("D 实现了 operation4");
  46. }
  47. public void operation5() {
  48. System.out.println("D 实现了 operation5");
  49. }
  50. }
  51. class A {
  52. // A 类通过接口 Interface1,Interface2 依赖(使用) B 类,但是只会用到 1,2,3 方法
  53. public void depend1(Interface1 i) {
  54. i.operation1();
  55. }
  56. public void depend2(Interface2 i) {
  57. i.operation2();
  58. }
  59. public void depend3(Interface2 i) {
  60. i.operation3();
  61. }
  62. }
  63. class C {
  64. // C 类通过接口 Interface1,Interface3 依赖(使用) D 类,但是只会用到 1,4,5 方法
  65. public void depend1(Interface1 i) {
  66. i.operation1();
  67. }
  68. public void depend4(Interface3 i) {
  69. i.operation4();
  70. }
  71. public void depend5(Interface3 i) {
  72. i.operation5();
  73. }
  74. }

3、依赖倒转原则

基本介绍

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

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

应用实例

编程完成 Person 接收消息 的功能。

方案1:

  1. package principle.inversion;
  2. public class DependecyInversion {
  3. public static void main(String[] args) {
  4. Person person = new Person();
  5. person.receive(new Email());
  6. }
  7. }
  8. class Email {
  9. public String getInfo() {
  10. return "电子邮件信息: hello,world";
  11. }
  12. }
  13. //完成 Person 接收消息的功能
  14. //方式 1 分析
  15. //1. 简单,比较容易想到
  16. //2. 如果我们获取的对象是 微信,短信等等,则新增类,同时 Perons 也要增加相应的接收方法
  17. //3. 解决思路:引入一个抽象的接口 IReceiver, 表示接收者, 这样 Person 类与接口 IReceiver 发生依赖
  18. // 因为 Email, WeiXin 等等属于接收的范围,他们各自实现 IReceiver 接口就 ok, 这样我们就符号依赖倒转原则
  19. class Person {
  20. public void receive(Email email ) {
  21. System.out.println(email.getInfo());
  22. }
  23. }

方案2:

  1. package principle.inversion.improve;
  2. public class DependecyInversion {
  3. public static void main(String[] args) {
  4. //客户端无需改变
  5. Person person = new Person(); person.receive(new Email());
  6. person.receive(new WeiXin());
  7. }
  8. }
  9. //定义接口
  10. interface IReceiver {
  11. public String getInfo();
  12. }
  13. class Email implements IReceiver {
  14. public String getInfo() {
  15. return "电子邮件信息: hello,world";
  16. }
  17. }
  18. //增加微信
  19. class WeiXin implements IReceiver {
  20. public String getInfo() {
  21. return "微信信息: hello,ok";
  22. }
  23. }
  24. //方式 2
  25. class Person {
  26. //这里我们是对接口的依赖
  27. public void receive(IReceiver receiver ) {
  28. System.out.println(receiver.getInfo());
  29. }
  30. }

依赖关系传递的三种方式和应用案例

1、接口传递

2、构造方法传递

3、setter 方式传递

  1. package principle.inversion.improve;
  2. public class DependencyPass {
  3. public static void main(String[] args) {
  4. ChangHong changHong = new ChangHong();
  5. // OpenAndClose openAndClose = new OpenAndClose();
  6. // openAndClose.open(changHong);
  7. // 通过构造器进行依赖传递
  8. // OpenAndClose openAndClose = new OpenAndClose(changHong);
  9. // openAndClose.open();
  10. // 通过 setter 方法进行依赖传递
  11. OpenAndClose openAndClose = new OpenAndClose();
  12. openAndClose.setTv(changHong);
  13. openAndClose.open();
  14. }
  15. }
  16. // 方式 1: 通过接口传递实现依赖
  17. // 开关的接口
  18. // interface IOpenAndClose {
  19. // public void open(ITV tv); //抽象方法,接收接口
  20. // }
  21. //
  22. // interface ITV { //ITV 接口
  23. // public void play();
  24. // }
  25. //
  26. // class ChangHong implements ITV {
  27. //
  28. // @Override
  29. // public void play() {
  30. // // TODO Auto-generated method stub
  31. // System.out.println("长虹电视机,打开");
  32. // }
  33. //
  34. // }
  35. 实现接口
  36. // class OpenAndClose implements IOpenAndClose{
  37. // public void open(ITV tv){
  38. // tv.play();
  39. // }
  40. // }
  41. // 方式 2: 通过构造方法依赖传递
  42. // interface IOpenAndClose {
  43. // public void open(); //抽象方法
  44. // }
  45. // interface ITV { //ITV 接口
  46. // public void play();
  47. // }
  48. // class OpenAndClose implements IOpenAndClose{
  49. // public ITV tv; //成员
  50. // public OpenAndClose(ITV tv){ //构造器
  51. // this.tv = tv;
  52. // }
  53. // public void open(){
  54. // this.tv.play();
  55. // }
  56. // }
  57. // 方式 3 , 通过 setter 方法传递
  58. interface IOpenAndClose {
  59. public void open(); // 抽象方法
  60. public void setTv(ITV tv);
  61. }
  62. interface ITV {
  63. // ITV 接口
  64. public void play();
  65. }
  66. class OpenAndClose implements IOpenAndClose {
  67. private ITV tv;
  68. public void setTv(ITV tv) {
  69. this.tv = tv;
  70. }
  71. public void open() {
  72. this.tv.play();
  73. }
  74. }
  75. class ChangHong implements ITV {
  76. @Override
  77. public void play() {
  78. System.out.println("长虹电视机,打开");
  79. }
  80. }

依赖倒转原则的注意事项和细节

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

4、里氏替换原则

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

1、继承包含这样一层含义:父类中凡是已经实现好的方法,实际上是在设定规范和契约,虽然它不强制要求所有的子类必须遵循这些契约,但是如果子类对这些已经实现的方法任意修改,就会对整个继承体系造成破坏。

2、继承在给程序设计带来便利的同时,也带来了弊端。比如使用继承会给程序带来侵入性,程序的可移植性降低, 增加对象间的耦合性,如果一个类被其他的类所继承,则当这个类需要修改时,必须考虑到所有的子类,并且父类修改后,所有涉及到子类的功能都有可能产生故障

3、问题提出:在编程中,如何正确的使用继承? => 里氏替换原则

基本介绍

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

一个程序引出的问题和思考

  1. package principle.liskov;
  2. public class Liskov {
  3. public static void main(String[] args) {
  4. A a = new A();
  5. System.out.println("11-3=" + a.func1(11, 3));
  6. System.out.println("1-8=" + a.func1(1, 8));
  7. System.out.println("-----------------------");
  8. B b = new B();
  9. System.out.println("11-3=" + b.func1(11, 3));//这里本意是求出 11-3
  10. System.out.println("1-8=" + b.func1(1, 8));// 1-8
  11. System.out.println("11+3+9=" + b.func2(11, 3));
  12. }
  13. }
  14. // A类
  15. class A {
  16. // 返回两个数的差
  17. public int func1(int num1, int num2) {
  18. return num1 - num2;
  19. }
  20. }
  21. // B 类继承了 A
  22. // 增加了一个新功能:完成两个数相加,然后和 9 求和
  23. class B extends A {
  24. //这里,重写了 A 类的方法, 可能是无意识
  25. public int func1(int a, int b) {
  26. return a + b;
  27. }
  28. public int func2(int a, int b) {
  29. return func1(a, b) + 9;
  30. }
  31. }

解决方法

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

在这里插入图片描述

  1. package principle.liskov.improve;
  2. public class Liskov {
  3. public static void main(String[] args) {
  4. A a = new A();
  5. System.out.println("11-3=" + a.func1(11, 3));
  6. System.out.println("1-8=" + a.func1(1, 8));
  7. System.out.println("-----------------------");
  8. B b = new B();
  9. //因为 B 类不再继承 A 类,因此调用者,不会再 func1 是求减法
  10. //调用完成的功能就会很明确
  11. System.out.println("11+3=" + b.func1(11, 3));//这里本意是求出 11+3
  12. System.out.println("1+8=" + b.func1(1, 8));// 1+8
  13. System.out.println("11+3+9=" + b.func2(11, 3));
  14. //使用组合仍然可以使用到 A 类相关方法
  15. System.out.println("11-3=" + b.func3(11, 3));// 这里本意是求出 11-3
  16. }
  17. }
  18. //创建一个更加基础的基类
  19. class Base {
  20. //把更加基础的方法和成员写到 Base 类
  21. }
  22. // A 类
  23. class A extends Base {
  24. // 返回两个数的差
  25. public int func1(int num1, int num2) {
  26. return num1 - num2;
  27. }
  28. }
  29. // B 类继承了 A
  30. // 增加了一个新功能:完成两个数相加,然后和 9 求和
  31. class B extends Base {
  32. //如果 B 需要使用 A 类的方法,使用组合关系
  33. private A a = new A();
  34. //这里,重写了 A 类的方法, 可能是无意识
  35. public int func1(int a, int b) {
  36. return a + b;
  37. }
  38. public int func2(int a, int b) {
  39. return func1(a, b) + 9;
  40. }
  41. //我们仍然想使用 A 的方法
  42. public int func3(int a, int b) {
  43. return this.a.func1(a, b);
  44. }
  45. }

5、开闭原则

基本介绍

1、开闭原则(Open Closed Principle)是编程中最基础、最重要的设计原则。

2、一个软件实体如类,模块和函数应该对扩展开放(对提供方),对修改关闭(对使用方)。用抽象构建框架,用实现扩展细节。

3、当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。

4、编程中遵循其它原则,以及使用设计模式的目的就是遵循开闭原则。

看一个画图形的功能

在这里插入图片描述

  1. package principle.ocp;
  2. public class Ocp {
  3. public static void main(String[] args) {
  4. //使用看看存在的问题
  5. GraphicEditor graphicEditor = new GraphicEditor();
  6. graphicEditor.drawShape(new Rectangle());
  7. graphicEditor.drawShape(new Circle());
  8. graphicEditor.drawShape(new Triangle());
  9. }
  10. }
  11. //这是一个用于绘图的类 [使用方]
  12. class GraphicEditor {
  13. //接收 Shape 对象,然后根据 type,来绘制不同的图形
  14. public void drawShape(Shape s) {
  15. if(s.m_type==1)
  16. drawRectangle(s);
  17. else if(s.m_type==2)
  18. drawCircle(s);
  19. else if(s.m_type==3)
  20. drawTriangle(s);
  21. }
  22. //绘制矩形
  23. public void drawRectangle(Shape r){
  24. System.out.println(" 绘制矩形 ");
  25. }
  26. //绘制圆形
  27. public void drawCircle(Shape r){
  28. System.out.println(" 绘制圆形 ");
  29. }
  30. //绘制三角形
  31. public void drawTriangle(Shape r){
  32. System.out.println(" 绘制三角形 ");
  33. }
  34. }
  35. //Shape 类,基类
  36. class Shape {
  37. int m_type;
  38. }
  39. class Rectangle extends Shape {
  40. Rectangle() {
  41. super.m_type = 1;
  42. }
  43. }
  44. class Circle extends Shape {
  45. Circle() {
  46. super.m_type = 2;
  47. }
  48. }
  49. //新增画三角形
  50. class Triangle extends Shape {
  51. Triangle() {
  52. super.m_type = 3;
  53. }
  54. }

方式 1 的优缺点

  1. 优点是比较好理解,简单易操作。
  2. 缺点是违反了设计模式的 ocp 原则,即对扩展开放(提供方),对修改关闭(使用方)。即当我们给类增加新功能的时候,尽量不修改代码,或者尽可能少修改代码.
  3. 比如我们这时要新增加一个图形种类 三角形,修改的地方较多

改进的思路分析

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

  1. package principle.ocp.improve;
  2. public class Ocp {
  3. public static void main(String[] args) {
  4. //使用看看存在的问题
  5. GraphicEditor graphicEditor = new GraphicEditor();
  6. graphicEditor.drawShape(new Rectangle());
  7. graphicEditor.drawShape(new Circle());
  8. graphicEditor.drawShape(new Triangle());
  9. graphicEditor.drawShape(new OtherGraphic());
  10. }
  11. }
  12. //这是一个用于绘图的类 [使用方]
  13. class GraphicEditor {
  14. //接收 Shape 对象,调用 draw 方法
  15. public void drawShape(Shape s) {
  16. s.draw();
  17. }
  18. }
  19. //Shape 类,基类
  20. abstract class Shape {
  21. int m_type;
  22. public abstract void draw();//抽象方法
  23. }
  24. class Rectangle extends Shape {
  25. Rectangle() {
  26. super.m_type = 1;
  27. }
  28. @Override
  29. public void draw() {
  30. System.out.println(" 绘制矩形 ");
  31. }
  32. }
  33. class Circle extends Shape {
  34. Circle() {
  35. super.m_type = 2;
  36. }
  37. @Override
  38. public void draw() {
  39. System.out.println(" 绘制圆形 ");
  40. }
  41. }
  42. //新增画三角形
  43. class Triangle extends Shape {
  44. Triangle() {
  45. super.m_type = 3;
  46. }
  47. @Override
  48. public void draw() {
  49. System.out.println(" 绘制三角形 ");
  50. }
  51. }
  52. //新增一个图形
  53. class OtherGraphic extends Shape {
  54. OtherGraphic() {
  55. super.m_type = 4;
  56. }
  57. @Override
  58. public void draw() {
  59. System.out.println(" 绘制其它图形 ");
  60. }
  61. }

6、迪米特法则

基本介绍

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

应用实例

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

  1. package principle.demeter;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. //客户端
  5. public class Demeter1 {
  6. public static void main(String[] args) {
  7. //创建了一个 SchoolManager 对象
  8. SchoolManager schoolManager = new SchoolManager();
  9. //输出学院的员工 id 和 学校总部的员工信息
  10. schoolManager.printAllEmployee(new CollegeManager());
  11. }
  12. }
  13. //学校总部员工类
  14. class Employee {
  15. private String id;
  16. public void setId(String id) {
  17. this.id = id;
  18. }
  19. public String getId() {
  20. return id;
  21. }
  22. }
  23. //学院的员工类
  24. class CollegeEmployee {
  25. private String id;
  26. public void setId(String id) {
  27. this.id = id;
  28. }
  29. public String getId() {
  30. return id;
  31. }
  32. }
  33. //管理学院员工的管理类
  34. class CollegeManager {
  35. //返回学院的所有员工
  36. public List<CollegeEmployee> getAllEmployee() {
  37. List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
  38. for (int i = 0; i < 10; i++) { //这里我们增加了 10 个员工到 list
  39. CollegeEmployee emp = new CollegeEmployee(); emp.setId("学院员工 id= " + i);
  40. list.add(emp);
  41. }
  42. return list;
  43. }
  44. }
  45. //学校管理类
  46. //分析 SchoolManager 类的直接朋友类有哪些 Employee、CollegeManager
  47. //CollegeEmployee 不是直接朋友 而是一个陌生类,这样违背了 迪米特法则
  48. class SchoolManager {
  49. //返回学校总部的员工
  50. public List<Employee> getAllEmployee() {
  51. List<Employee> list = new ArrayList<Employee>();
  52. for (int i = 0; i < 5; i++) { //这里我们增加了 5 个员工到 list
  53. Employee emp = new Employee();
  54. emp.setId("学校总部员工 id= " + i);
  55. list.add(emp);
  56. }
  57. return list;
  58. }
  59. //该方法完成输出学校总部和学院员工信息(id)
  60. void printAllEmployee(CollegeManager sub) {
  61. //分析问题
  62. //1. 这里的 CollegeEmployee 不是 SchoolManager 的直接朋友
  63. //2. CollegeEmployee 是以局部变量方式出现在 SchoolManager
  64. //3. 违反了 迪米特法则
  65. //获取到学院员工
  66. List<CollegeEmployee> list1 = sub.getAllEmployee();
  67. System.out.println("------------学院员工------------");
  68. for (CollegeEmployee e : list1) {
  69. System.out.println(e.getId());
  70. }
  71. //获取到学校总部员工
  72. List<Employee> list2 = this.getAllEmployee();
  73. System.out.println("------------学校总部员工------------");
  74. for (Employee e : list2) {
  75. System.out.println(e.getId());
  76. }
  77. }
  78. }

应用实例改进

1、前面设计的问题在于 SchoolManager 中,CollegeEmployee 类并不是 SchoolManager 类的直接朋友 (分析)

2、按照迪米特法则,应该避免类中出现这样非直接朋友关系的耦合

3、对代码按照迪米特法则 进行改进

  1. package principle.demeter.improve;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. public class Demeter1 {
  5. public static void main(String[] args) {
  6. System.out.println("~~~使用迪米特法则的改进~~~");
  7. //创建了一个 SchoolManager 对象
  8. SchoolManager schoolManager = new SchoolManager();
  9. //输出学院的员工 id 和 学校总部的员工信息
  10. schoolManager.printAllEmployee(new CollegeManager());
  11. }
  12. }
  13. //学校总部员工类
  14. class Employee {
  15. private String id;
  16. public void setId(String id) {
  17. this.id = id;
  18. }
  19. public String getId() {
  20. return id;
  21. }
  22. }
  23. //学院的员工类
  24. class CollegeEmployee {
  25. private String id;
  26. public void setId(String id) {
  27. this.id = id;
  28. }
  29. public String getId() {
  30. return id;
  31. }
  32. }
  33. //管理学院员工的管理类
  34. class CollegeManager {
  35. //返回学院的所有员工
  36. public List<CollegeEmployee> getAllEmployee() {
  37. List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
  38. for (int i = 0; i < 10; i++) { //这里我们增加了 10 个员工到 list
  39. CollegeEmployee emp = new CollegeEmployee();
  40. emp.setId("学院员工 id= " + i); list.add(emp);
  41. }
  42. return list;
  43. }
  44. // 输 出 学 院 员 工 的 信 息
  45. public void printEmployee() {
  46. //获取到学院员工
  47. List<CollegeEmployee> list1 = getAllEmployee();
  48. System.out.println("------------学院员工------------");
  49. for (CollegeEmployee e : list1) {
  50. System.out.println(e.getId());
  51. }
  52. }
  53. }
  54. //学校管理类
  55. //分析 SchoolManager 类的直接朋友类有哪些 Employee、CollegeManager
  56. //CollegeEmployee 不是 直接朋友 而是一个陌生类,这样违背了 迪米特法则
  57. class SchoolManager {
  58. //返回学校总部的员工
  59. public List<Employee> getAllEmployee() {
  60. List<Employee> list = new ArrayList<Employee>();
  61. for (int i = 0; i < 5; i++) { //这里我们增加了 5 个员工到 list
  62. Employee emp = new Employee();
  63. emp.setId("学校总部员工 id= " + i); list.add(emp);
  64. }
  65. return list;
  66. }
  67. //该方法完成输出学校总部和学院员工信息(id)
  68. void printAllEmployee(CollegeManager sub) {
  69. //分析问题
  70. //1. 将输出学院的员工方法,封装到 CollegeManager
  71. sub.printEmployee();
  72. //获取到学校总部员工
  73. List<Employee> list2 = this.getAllEmployee();
  74. System.out.println("------------学校总部员工------------");
  75. for (Employee e : list2) {
  76. System.out.println(e.getId());
  77. }
  78. }
  79. }

迪米特法则注意事项和细节

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

7、合成复用原则(Composite Reuse Principle)

基本介绍

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

在这里插入图片描述

三、设计原则核心思想

1、找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起。

2、针对接口编程,而不是针对实现编程。

3、为了交互对象之间的松耦合设计而努力

发表评论

表情:
评论列表 (有 0 条评论,270人围观)

还没有评论,来说两句吧...

相关阅读

    相关 设计模式-原则

    1.设计模式的目的 设计模式是为了让程序(软件), 具有更好 1. 代码重用性 (即: 相同功能的代码, 不用多次编写) 2. 可读性 (即: 编程规范性, 便于其

    相关 设计模式原则

    引言 设计模式如单例模式、工厂模式、适配器模式等,大概有二十多种,但是这些设计模式的背后,有七大设计基本原则。 它们分别是:单一职责原则,接口隔离原则,依赖倒转原则,里

    相关 设计模式原则

      我们在开发过程中常常使用设计模式 但使用设计模式时候 我们又是否知道设计模式的一些设计原则呢? 今天我们就来盘一下设计模式七大原则,它们分别是:   1.开闭原则