7.5 GRASP原则五:高内聚 High Cohesion

GRASP原则五:高内聚 High Cohesion
   How to keep objects focused, understandable and manageable, and as a side effect support Low Coupling?

    如何使对象功能专注、可理解、可管理,同时又支持 低耦合?
5.1 GRASP rule 5:High Cohesion

   Name:High Cohesion 高内聚

   Problem:

     How to keep objects focused, understandable and manageable, and as a side effect support Low Coupling?

   Solution:

     Assign responsibility so cohesion remains high 分配职责时保证高内聚

   Dosage(用法):

     Used as an evaluation tool 用作评价工具

     更多的是一种理念,没有具体的可操作原则
5.2 Cohesion Defined

   衡量概念之间相关度的两个指标

     Cohesion,内聚:模块内元素之间联系紧密的程度,比如,一个类内部的操作之间

     Coupling,耦合:两个模块之间联系的强度

   内聚的“最佳实践”

     一个对象完成的功能不要太多 small number of responsibilities

     这些功能都是同一类别的 highly related responsibilities

     例如,教授:主要任务就是教学;研究员:主要任务是科研

   评判练习,哪个更内聚

     一个类有2000行源代码100个方法

     另一个类有200行源代码10个方法

     谁能保证任务重的对象在完成功能时不会引用到类外部的资源(增加了耦合度)

   比喻: “不是一家人,不进一家门”

     “人” compared to “职责、操作”

     “门” compared to “模块、类”
5.4 Discuss: Cohesion

   类低内聚的具有症状 A class with low cohesion

     做了许多相互无关的工作 does many unrelated things

     做了太多工作 does too much work

   类低内聚的的原因 Low cohesion classes often represent

     大粒度的抽象 a very large grain of abstraction

     做了太多本应该委托给其他类去做的工作 have taken on responsibilities that should have been delegated to other objects

   类低内聚的问题

     难以理解 Hard to understand

     难以重用 Hard to reuse

     难以维护 Hard to maintain

     没有稳定的时刻,总是在修改 (通常都会高耦合)
小结

   高内聚的类

     有较少数量的操作,操作的性质基本一致,不会做太多的事情

     如果同类别的工作太多,则会定义新的类分担任务,相互间合作

   高内聚的类有许多有点

     易于维护

     易于理解

     易于重用

   高内聚也是一种评估性原则,用于评估所有的设计决策是否合适

    It is an evaluative principle that a designer applies while evaluating all design decisions

原文地址:https://www.cnblogs.com/mayZhou/p/10550041.html