设计模式:七大设计原则

设计模式是为了让程序具有更好的

代码重用性(相同功能的代码,不用多次编写)

可读性(编程规范性,便于其他程序员的阅读和理解)

可扩展性(当需要增加新的功能时,非常的方便,称为可维护)

可靠性(当我们增加新的功能后,对原来的功能没有影响)

使程序呈现高内聚,低耦合的特性。

一、单一职责

1、基本介绍

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

2、注意事项和细节

降低类的复杂度,一个类只负责一项职责。

提高类的可读性,可维护性。

降低变更引起的风险。

通常情况下,我们应当遵守单一职责原则(一个类只负责一项职责)。只有在逻辑足够简单,才可以在代码级违反单一职责原则;只有类中方法数量足够少,才可以在方法级别保持单一原则。(可参照代码Demo3)

3、代码实现案例

(1)Demo1(违反了单一职责原则)
  1. package com.dashu.principle.single_responsibility;
  2. public class SinglenessDemo {
  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. * 问题:
  12. * 在该Demo中,类Vehicle违反了单一职责原则。包含了同时在三中场景运行的交通工具(水路空);同时汽车和轮船不应该在公路上运行
  13. * <p>
  14. * 解决:
  15. * 遵守单一职责原则。根据交通工具运行场景不同,分解成不同的类。
  16. */
  17. /**
  18. * 交通工具
  19. */
  20. class Vehicle {
  21. public void run(String vehicle) {
  22. System.out.println(vehicle + "在公路上运行。。。");
  23. }
  24. }

(2)Demo2(采用单一职责原则)
  1. package com.dashu.principle.single_responsibility;
  2. public class SinglenessDemo {
  3. public static void main(String[] args) {
  4. RoadVehicle roadVehicle = new RoadVehicle();
  5. roadVehicle.run("汽车");
  6. AirVehicle airVehicle = new AirVehicle();
  7. airVehicle.run("飞机");
  8. WaterVehicle waterVehicle = new WaterVehicle();
  9. waterVehicle.run("轮船");
  10. }
  11. }
  12. /**
  13. * 问题:
  14. * 在该Demo中,遵守了单一职责原则
  15. * 但是这样做的改动很大(Demo逻辑很简单),即将类分解了,同时修改客户端
  16. * <p>
  17. * 解决:
  18. * 直接修改Vehicle类,在方法层级上实现单一职责原则
  19. */
  20. /**
  21. * 道路交通工具
  22. */
  23. class RoadVehicle {
  24. public void run(String vehicle) {
  25. System.out.println(vehicle + "在公路上运行。。。");
  26. }
  27. }
  28. /**
  29. * 天空交通工具
  30. */
  31. class AirVehicle {
  32. public void run(String vehicle) {
  33. System.out.println(vehicle + "在天空中运行。。。");
  34. }
  35. }
  36. /**
  37. * 水上交通工具
  38. */
  39. class WaterVehicle {
  40. public void run(String vehicle) {
  41. System.out.println(vehicle + "在水上运行。。。");
  42. }
  43. }

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

二、接口隔离原则

1、基本介绍

一个类对另外一个类的依赖应该建立在最小接口上。

2、案例

3、改进

4、代码实现案例

(1)Demo1(违反接口隔离原则)
  1. /**
  2. * 接口F
  3. */
  4. public interface F {
  5. public void a();
  6. public void b();
  7. public void c();
  8. public void d();
  9. public void e();
  10. }
  1. /**
  2. * 接口F实现类A
  3. */
  4. public class A implements F {
  5. @Override
  6. public void a() {
  7. }
  8. @Override
  9. public void b() {
  10. }
  11. @Override
  12. public void c() {
  13. }
  14. @Override
  15. public void d() {
  16. }
  17. @Override
  18. public void e() {
  19. }
  20. }
  1. /**
  2. * 接口F实现类B
  3. */
  4. public class B implements F {
  5. @Override
  6. public void a() {
  7. }
  8. @Override
  9. public void b() {
  10. }
  11. @Override
  12. public void c() {
  13. }
  14. @Override
  15. public void d() {
  16. }
  17. @Override
  18. public void e() {
  19. }
  20. }
  1. public class C {
  2. /**
  3. * 类C依赖接口F,使用了abc三个方法
  4. */
  5. public void test() {
  6. F f = new A();
  7. f.a();
  8. f.b();
  9. f.c();
  10. }
  11. }
  1. public class D {
  2. /**
  3. * 类D依赖接口F,使用了ade三个方法
  4. */
  5. public void test() {
  6. F f = new B();
  7. f.a();
  8. f.d();
  9. f.e();
  10. }
  11. }

(2)Demo2(采用接口隔离原则)
  1. /**
  2. * 接口F
  3. */
  4. public interface F {
  5. public void a();
  6. }
  1. /**
  2. * 接口G
  3. */
  4. public interface G {
  5. public void b();
  6. public void c();
  7. }
  1. /**
  2. * 接口H
  3. */
  4. public interface H {
  5. public void d();
  6. public void e();
  7. }
  1. /**
  2. * 接口F,G实现类A
  3. */
  4. public class A implements F, G {
  5. @Override
  6. public void a() {
  7. }
  8. @Override
  9. public void b() {
  10. }
  11. @Override
  12. public void c() {
  13. }
  14. }
  1. /**
  2. * 接口F,H实现类B
  3. */
  4. public class B implements F,H {
  5. @Override
  6. public void a() {
  7. }
  8. @Override
  9. public void d() {
  10. }
  11. @Override
  12. public void e() {
  13. }
  14. }
  1. public class C {
  2. /**
  3. * 类C依赖接口F,G。使用了abc三个方法
  4. */
  5. public void test() {
  6. F f = new A();
  7. G g = new A();
  8. f.a();
  9. g.b();
  10. g.c();
  11. }
  12. }
  1. public class D {
  2. /**
  3. * 类C依赖接口F,H。使用了ade三个方法
  4. */
  5. public void test() {
  6. F f = new B();
  7. H h = new B();
  8. f.a();
  9. h.d();
  10. h.e();
  11. }
  12. }

三、依赖倒转原则

1、基本介绍

依赖倒转原则是指:

  • 高层模块不应该依赖低层模块,二者都应该依赖其抽象
  • 抽象不应该依赖细节,细节应该依赖抽象
  • 依赖倒转的中心思想就是面接接口编程

设计理念:相对于细节的多变性,抽象的东西要稳定得多。以抽象为基础搭建的架构比以细节为基础的架构要稳定得多。在java中,抽象指的就是接口和抽象类,细节就是具体的实现类

使用接口或抽象类的目的就是为了制定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类去完成。

2、案例

3、改进

4、代码实现案例

(1)Demo1(违反依赖倒转原则)
  1. public class QQ {
  2. public void message(){
  3. System.out.println("QQ消息");
  4. }
  5. }
  1. public class WX {
  2. public void message(){
  3. System.out.println("微信消息");
  4. }
  5. }
  1. public class Email {
  2. public void message(){
  3. System.out.println("Email消息");
  4. }
  5. }
  1. public class User {
  2. public void receive(QQ qq){
  3. qq.message();
  4. }
  5. public void receive(WX wx){
  6. wx.message();
  7. }
  8. public void receive(Email email){
  9. email.message();
  10. }
  11. }
  1. public class Client {
  2. public static void main(String[] args) {
  3. User user = new User();
  4. user.receive(new QQ());
  5. user.receive(new WX());
  6. user.receive(new Email());
  7. }
  8. }

(2)Demo2(遵循依赖倒转原则)
  1. public interface Message {
  2. void message();
  3. }
  1. public class QQ implements Message{
  2. @Override
  3. public void message(){
  4. System.out.println("QQ消息");
  5. }
  6. }
  1. public class WX implements Message{
  2. @Override
  3. public void message(){
  4. System.out.println("微信消息");
  5. }
  6. }
  1. public class Email implements Message{
  2. @Override
  3. public void message(){
  4. System.out.println("Email消息");
  5. }
  6. }
  1. public class User {
  2. public void receive(Message message) {
  3. message.message();
  4. }
  5. }
  1. public class Client {
  2. public static void main(String[] args) {
  3. User user = new User();
  4. user.receive(new QQ());
  5. user.receive(new WX());
  6. user.receive(new Email());
  7. }
  8. }

5、比对

当我们想要接收短信类型的消息时,Demo1不仅需要添加一个短信类型的消息类(Note),同时也要再在User类中添加一个用于接收短信类型的方法

  1. public void receive(Note note){
  2. note.message();
  3. }

而Demo2中,我们只需要添加一个短信类型的消息类(Note),并实现接口Message

6、依赖关系传递的三种方式

(1)通过接口传递依赖
  1. public interface OpenAndClose {
  2. void open(Tv tv);
  3. }
  1. public class OpenAndCloseImpl implements OpenAndClose{
  2. @Override
  3. public void open(Tv tv) {
  4. tv.play();
  5. }
  6. }
  1. public interface Tv {
  2. void play();
  3. }
  1. public class ChangHong implements Tv{
  2. @Override
  3. public void play() {
  4. System.out.println("长虹电视机,打开");
  5. }
  6. }
  1. /**
  2. * 通过接口传递依赖
  3. */
  4. public class Client {
  5. public static void main(String[] args) {
  6. ChangHong changHong = new ChangHong();
  7. OpenAndClose openAndClose = new OpenAndCloseImpl();
  8. openAndClose.open(changHong);
  9. }
  10. }

(2)通过构造方法传递依赖
  1. public interface OpenAndClose {
  2. void open();
  3. }
  1. public class OpenAndCloseImpl implements OpenAndClose {
  2. private Tv tv;
  3. public OpenAndCloseImpl(Tv tv){
  4. this.tv = tv;
  5. }
  6. @Override
  7. public void open() {
  8. tv.play();
  9. }
  10. }
  1. public interface Tv {
  2. void play();
  3. }
  1. public class ChangHong implements Tv {
  2. @Override
  3. public void play() {
  4. System.out.println("长虹电视机,打开");
  5. }
  6. }
  1. /**
  2. * 通过构造方法传递依赖
  3. */
  4. public class Client {
  5. public static void main(String[] args) {
  6. ChangHong changHong = new ChangHong();
  7. OpenAndClose openAndClose = new OpenAndCloseImpl(changHong);
  8. openAndClose.open();
  9. }
  10. }

(3)通过setter方法传递依赖
  1. public interface OpenAndClose {
  2. void open();
  3. void setTv(Tv tv);
  4. }
  1. public class OpenAndCloseImpl implements OpenAndClose {
  2. private Tv tv;
  3. @Override
  4. public void open() {
  5. tv.play();
  6. }
  7. @Override
  8. public void setTv(Tv tv) {
  9. this.tv = tv;
  10. }
  11. }
  1. public interface Tv {
  2. void play();
  3. }
  1. public class ChangHong implements Tv {
  2. @Override
  3. public void play() {
  4. System.out.println("长虹电视机,打开");
  5. }
  6. }
  1. /**
  2. * 通过setter方法传递依赖
  3. */
  4. public class Client {
  5. public static void main(String[] args) {
  6. ChangHong changHong = new ChangHong();
  7. OpenAndClose openAndClose = new OpenAndCloseImpl();
  8. openAndClose.setTv(changHong);
  9. openAndClose.open();
  10. }
  11. }

四、里氏替换原则

1、面向对象中继承性得思考和说明

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

2、里氏替换原则

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

3、代码实现案例

(1)Demo1(违反里氏替换原则)
  1. public class A {
  2. public int func1(int x,int y){
  3. return x-y;
  4. }
  5. }
  1. public class B extends A{
  2. @Override
  3. public int func1(int x, int y){
  4. return x-y;
  5. }
  6. }
  1. public class Client {
  2. public static void main(String[] args) {
  3. A a = new A();
  4. System.out.println(a.func1(10, 5));
  5. A b = new B();
  6. /**
  7. * 这里本意是调用父类A的func1方法计算x与y的和,但是子类B重写了func1方法,导致结果为计算x与y的差。所以引起程序错误
  8. */
  9. System.out.println(b.func1(10, 5));
  10. }
  11. }

(2)Demo2(遵循里氏替换原则)
  1. public class Base {
  2. }
  1. public class A extends Base {
  2. public int func1(int x, int y) {
  3. return x + y;
  4. }
  5. }
  1. public class B extends Base {
  2. A a = new A();
  3. public int func1(int x, int y) {
  4. return x - y;
  5. }
  6. public int func2(int x, int y) {
  7. return a.func1(x, y);
  8. }
  9. }
  1. /**
  2. * 类A和类B继承一个更加基础的类,如果类B想要使用类A的func1方法,则通过依赖A来使用func1方法。
  3. */
  4. public class Client {
  5. public static void main(String[] args) {
  6. A a = new A();
  7. B b = new B();
  8. System.out.println(a.func1(10, 5));
  9. System.out.println(b.func1(10, 5));
  10. System.out.println(b.func2(10, 5));
  11. }
  12. }

五、开闭原则

1、基本介绍

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

2、代码实现案列

(1)Demo1(违反开闭原则)
  1. /**
  2. * 形状
  3. */
  4. public class Shape {
  5. int type;
  6. }
  1. /**
  2. * 圆形
  3. */
  4. public class Circle extends Shape{
  5. Circle() {
  6. super.type=2;
  7. }
  8. }
  1. /**
  2. * 三角形
  3. */
  4. public class Triangle extends Shape{
  5. Triangle() {
  6. super.type=3;
  7. }
  8. }
  1. /**
  2. * 矩形
  3. */
  4. public class Rectangle extends Shape{
  5. Rectangle() {
  6. super.type=1;
  7. }
  8. }
  1. /**
  2. * 绘图
  3. */
  4. public class GraphicEditor {
  5. public void drawShape(Shape shape) {
  6. if (shape.type == 1) {
  7. drawRectangle(shape);
  8. } else if (shape.type == 2) {
  9. drawCircle(shape);
  10. } else if (shape.type == 3) {
  11. drawTriangle(shape);
  12. }
  13. }
  14. private void drawTriangle(Shape shape) {
  15. System.out.println("绘制三角形");
  16. }
  17. private void drawCircle(Shape shape) {
  18. System.out.println("绘制圆形");
  19. }
  20. private void drawRectangle(Shape shape) {
  21. System.out.println("绘制矩形");
  22. }
  23. }
  1. /**
  2. * 该方式唯一的有点就是简单,容易理解。但是严重违反了开闭原则
  3. *
  4. * 当我们添加一个五角形
  5. * 1、添加一个五角星类
  6. * 2、在“GraphicEditor”添加一个绘画五角星的方法,
  7. * 3、在方法“drawShape”中添加一个条件判断
  8. *
  9. */
  10. public class Client {
  11. public static void main(String[] args) {
  12. GraphicEditor graphicEditor = new GraphicEditor();
  13. graphicEditor.drawShape(new Rectangle());
  14. graphicEditor.drawShape(new Circle());
  15. graphicEditor.drawShape(new Triangle());
  16. }
  17. }

(2)Demo2(遵循开闭原则)
  1. /**
  2. * 图形接口
  3. */
  4. public interface Shape {
  5. void draw();
  6. }
  1. /**
  2. * 圆形
  3. */
  4. public class Circle implements Shape {
  5. @Override
  6. public void draw() {
  7. System.out.println("绘画圆形");
  8. }
  9. }
  1. /**
  2. * 矩形
  3. */
  4. public class Rectangle implements Shape {
  5. @Override
  6. public void draw() {
  7. System.out.println("绘画矩形");
  8. }
  9. }
  1. /**
  2. * 三角形
  3. */
  4. public class Triangle implements Shape {
  5. @Override
  6. public void draw() {
  7. System.out.println("绘画三角形");
  8. }
  9. }
  1. /**
  2. * 绘图
  3. */
  4. public class GraphicEditor {
  5. public void drawShape(Shape shape) {
  6. shape.draw();
  7. }
  8. }
  1. /**
  2. * 该方式遵循了开闭原则
  3. *
  4. * 当我们添加一个五角形,只需要添加一个五角星类就可以了
  5. *
  6. *
  7. */
  8. public class Client {
  9. public static void main(String[] args) {
  10. GraphicEditor graphicEditor = new GraphicEditor();
  11. graphicEditor.drawShape(new Rectangle());
  12. graphicEditor.drawShape(new Circle());
  13. graphicEditor.drawShape(new Triangle());
  14. }
  15. }

六、迪米特法则

1、基本介绍

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

2、代码实现案列

(1)Demo1(违反迪米特法则)
  1. /**
  2. * 学校员工类
  3. */
  4. public class CollegeEmployee {
  5. private String id;
  6. public String getId() {
  7. return id;
  8. }
  9. public void setId(String id) {
  10. this.id = id;
  11. }
  12. }
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. /**
  4. * 学校员工的管理类
  5. */
  6. public class CollegeManager {
  7. public List<CollegeEmployee> getEmployeeList() {
  8. ArrayList<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
  9. for (int i = 0; i < 10;i++) {
  10. CollegeEmployee collegeEmployee = new CollegeEmployee();
  11. collegeEmployee.setId("学院员工id="+i);
  12. list.add(collegeEmployee);
  13. }
  14. return list;
  15. }
  16. }
  1. /**
  2. * 学校总部员工类
  3. */
  4. public class Employee {
  5. private String id;
  6. public String getId() {
  7. return id;
  8. }
  9. public void setId(String id) {
  10. this.id = id;
  11. }
  12. }
  1. /**
  2. * 学校管理类
  3. */
  4. public class SchoolManager {
  5. public List<Employee> getEmployeeList() {
  6. ArrayList<Employee> list = new ArrayList<Employee>();
  7. for (int i = 0; i < 5; i++) {
  8. Employee employee = new Employee();
  9. employee.setId("学校总部员工id=" + i);
  10. list.add(employee);
  11. }
  12. return list;
  13. }
  14. void printEmployee(CollegeManager c) {
  15. List<CollegeEmployee> employeeList = c.getEmployeeList();
  16. System.out.println("学院员工");
  17. for (CollegeEmployee employee : employeeList) {
  18. System.out.println(employee.getId());
  19. }
  20. System.out.println("-----------------------");
  21. List<Employee> employeeList1 = getEmployeeList();
  22. System.out.println("学院总部员工");
  23. for (Employee employee : employeeList1) {
  24. System.out.println(employee.getId());
  25. }
  26. }
  27. }
  1. /**
  2. * CollegeEmployee不是SchoolManager的直接朋友
  3. * <p>
  4. * 类SchoolManager的方法printEmployee使用了一个陌生类CollegeEmployee,违反了迪米特法则。
  5. */
  6. public class Client {
  7. public static void main(String[] args) {
  8. SchoolManager schoolManager = new SchoolManager();
  9. schoolManager.printEmployee(new CollegeManager());
  10. }
  11. }

(2)Demo2(遵循迪米特法则)
  1. /**
  2. * 学校员工类
  3. */
  4. public class CollegeEmployee {
  5. private String id;
  6. public String getId() {
  7. return id;
  8. }
  9. public void setId(String id) {
  10. this.id = id;
  11. }
  12. }
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. /**
  4. * 学校员工的管理类
  5. */
  6. public class CollegeManager {
  7. public List<CollegeEmployee> getEmployeeList() {
  8. ArrayList<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
  9. for (int i = 0; i < 10; i++) {
  10. CollegeEmployee collegeEmployee = new CollegeEmployee();
  11. collegeEmployee.setId("学院员工id=" + i);
  12. list.add(collegeEmployee);
  13. }
  14. return list;
  15. }
  16. void printEmployee() {
  17. List<CollegeEmployee> employeeList = getEmployeeList();
  18. System.out.println("学院员工");
  19. for (CollegeEmployee employee : employeeList) {
  20. System.out.println(employee.getId());
  21. }
  22. }
  23. }
  1. /**
  2. * 学校总部员工类
  3. */
  4. public class Employee {
  5. private String id;
  6. public String getId() {
  7. return id;
  8. }
  9. public void setId(String id) {
  10. this.id = id;
  11. }
  12. }
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. /**
  4. * 学校管理类
  5. */
  6. public class SchoolManager {
  7. public List<Employee> getEmployeeList() {
  8. ArrayList<Employee> list = new ArrayList<Employee>();
  9. for (int i = 0; i < 5; i++) {
  10. Employee employee = new Employee();
  11. employee.setId("学校总部员工id=" + i);
  12. list.add(employee);
  13. }
  14. return list;
  15. }
  16. void printEmployee(CollegeManager c) {
  17. c.printEmployee();
  18. System.out.println("-----------------------");
  19. List<Employee> employeeList1 = getEmployeeList();
  20. System.out.println("学院总部员工");
  21. for (Employee employee : employeeList1) {
  22. System.out.println(employee.getId());
  23. }
  24. }
  25. }
  1. /**
  2. * 遵循迪米特法则,只与直接朋友通信
  3. */
  4. public class Client {
  5. public static void main(String[] args) {
  6. SchoolManager schoolManager = new SchoolManager();
  7. schoolManager.printEmployee(new CollegeManager());
  8. }
  9. }

七、合成复用原则

1、基本介绍

合成复用原则(Composite Reuse Principle,CRP)又叫组合/聚合复用原则(Composition/Aggregate Reuse Principle,CARP)。它要求在软件复用时,要尽量先使用组合或者聚合等关联关系来实现,其次才考虑使用继承关系来实现。

如果要使用继承关系,则必须严格遵循里氏替换原则。合成复用原则同里氏替换原则相辅相成的,两者都是开闭原则的具体实现规范。

合成复用原则的重要性

通常类的复用分为继承复用和合成复用两种,

继承复用虽然有简单和易实现的优点,但它也存在以下缺点。
  继承复用破坏了类的封装性。因为继承会将父类的实现细节暴露给子类,父类对子类是透明的,所以这种复用又称为“白箱”复用。
  子类与父类的耦合度高。父类的实现的任何改变都会导致子类的实现发生变化,这不利于类的扩展与维护。
  它限制了复用的灵活性。从父类继承而来的实现是静态的,在编译时已经定义,所以在运行时不可能发生变化。

采用组合或聚合复用时,可以将已有对象纳入新对象中,使之成为新对象的一部分,新对象可以调用已有对象的功能,它有以下优点。
  它维持了类的封装性。因为成分对象的内部细节是新对象看不见的,所以这种复用又称为“黑箱”复用。
  新旧类之间的耦合度低。这种复用所需的依赖较少,新对象存取成分对象的唯一方法是通过成分对象的接口。
  3复用的灵活性高。这种复用可以在运行时动态进行,新对象可以动态地引用与成分对象类型相同的对象。