1、单一设计原则(Single Responsibility Principle)

1.1 定义

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

1.2 应用实例

1) 方案一

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

2)方案二

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

3) 方案3

  1. public class SingleResponsibility3 {
  2. public static void main(String[] args) {
  3. Vehicle2 vehicle2 = new Vehicle2();
  4. vehicle2.run("汽车");
  5. vehicle2.runWater("轮船");
  6. vehicle2.runAir("飞机");
  7. }
  8. }
  9. //方式3的分析
  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.
  24. //..
  25. //..
  26. //...
  27. }

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

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

2.1 定义

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

2.2 应用实例

七大设计原则 - 图1

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

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

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

七大设计原则 - 图2

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

2.3 注意事项和细节
  • 接口尽量小,但是要有限度。对接口进行细化可以提高程序设计灵活是不挣的事实,但是如果过小,则会造成接口数量过多,使设计复杂化。所以一定要适度。
  • 为依赖接口的类定制服务,只暴露给调用的类它需要的方法,它不需要的方法则隐藏起来。只有专注地为一个模块提供定制服务,才能建立最小的依赖关系。
  • 提高内聚,减少对外交互,使接口用最小的方法去完成最多的事情。

2.4 单一职责原理VS接口隔离原则
  • 单一职责原则注重的是职责;而接口隔离原则注重对接口依赖的隔离。
  • 单一职责原则主要是约束类,其次才是接口和方法,它针对的是程序中的实现和细节;而接口隔离原则主要约束接口,主要针对抽象,针对程序整体框架的构建。

3、依赖倒转原则(Dependence Inversion Principle)

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

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

依赖倒转改进方案:

  1. public class DependecyInversion {
  2. public static void main(String[] args) {
  3. //客户端无需改变
  4. Person person = new Person();
  5. 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. }

3.3 传递依赖关系的方式

3.3.1 三种方式

  • 接口传递。
  • 构造方式传递。
  • setter方法传递。

3.3.2 应用案例

  1. public class DependencyPass {
  2. public static void main(String[] args) {
  3. // TODO Auto-generated method stub
  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 { // ITV接口
  63. public void play();
  64. }
  65. class OpenAndClose implements IOpenAndClose {
  66. private ITV tv;
  67. public void setTv(ITV tv) {
  68. this.tv = tv;
  69. }
  70. public void open() {
  71. this.tv.play();
  72. }
  73. }
  74. class ChangHong implements ITV {
  75. @Override
  76. public void play() {
  77. // TODO Auto-generated method stub
  78. System.out.println("长虹电视机,打开");
  79. }
  80. }

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

4、里氏替换原则(Liskov Substition Principle)

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

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

4.3 应用案例

  1. public class Liskov {
  2. public static void main(String[] args) {
  3. // TODO Auto-generated method stub
  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. public class Liskov {
  2. public static void main(String[] args) {
  3. // TODO Auto-generated method stub
  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. }

4.4 注意事项和细节

里氏替换原则通俗的来讲就是:子类可以扩展父类的功能,但不能改变父类原有的功能。它包含以下4层含义:

  • 子类可以实现父类的抽象方法,但不能覆盖父类的非抽象方法。
  • 子类中可以增加自己特有的方法。
  • 当子类的方法重载父类的抽象方法时,方法的前置条件(即方法的形参)要比父类方法的输入参数更宽松。
  • 放子类的方法实现父类的抽象方法时,方法的后置条件(即方法的返回值)要比父类更严格。

5、开闭原则(Open Closed Priciple)

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

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

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

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

6、迪米特法则(Demeter Principle)

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

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

改进方法:

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

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

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

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

七大设计原则 - 图3