设计模式始记——五分钟学UML

工欲善其事,必先利其器

在网上看各种设计模式的书籍,常常会看到各种各样的图表,比如:


下面的这个Chrome插件可以帮助我们一秒钟拥有老司机的作图能力

鲜为人知的Chrome插件
What's the best UML diagramming tool?
Gliffy插件地址

UML图基础知识

  • Generalization/extends


    B **is a kind of** A

    扩展关系示例

更多示例资源
Generalization, Specialization, and Inheritance
UML Class Diagram Generalization Example

  • Implements


    B实现A接口

    接口实现实例
  • Dependencty

Dependency is a weaker form of bond that indicates that one class depends on another because it uses it at some point in time. One class depends on another if the independent class is a parameter variable or local variable of a method of the dependent class. This is different from an association, where an attribute of the dependent class is an instance of the independent class. Sometimes the relationship between two classes is very weak. They are not implemented with member variables at all. Rather they might be implemented as member function arguments.
Dependency is often confused as Association. Dependency is normally created when you receive a reference to a class as part of a particular operation / method. Dependency indicates that you may invoke one of the APIs of the received class reference and any modification to that class may break your class as well.

B依赖于A


依赖关系示例
class Ball{ public void kick() { ... } }
class Player{
    public void takeTurn(Ball ball) { /*Player dependent on ball*/
      ball.kick(); 
    }
}
  • Association

Association is a relationship where all objects have their own lifecycle and there is no owner
Association关系可以用带方向的箭头连接两个类,如果说是无向线段连接两个类,那么这两个类之间就是双向关联

A和B**有关联,但各自可以独立存在**

Association示例
class Goods{ ... }
class Buyer{
    Goods  goods;
    public Buyer(Goods purchasedGoods) {
        ... 
    } /*goods通过constructor传入*/
}
  • Aggregation

Aggregation is a specialised form of Association where all objects have their own lifecycle, but there is ownership and child objects can not belong to another parent object.

A **has a** B,B可以**独立存在**于A之外


Aggregation示例
  • Composition

Composition is again specialised form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object does not have its lifecycle and if parent object is deleted, all child objects will also be deleted.

A中有B,但B依赖于A,**无法脱离**A

Composition关系示例
Association、Aggregation、Composition三者关系

参考资料
Wikipedia:Class diagram
UML中关联(Association)、聚合(Aggregation)和合成(Composition)之间的区别
Understanding UML Class Relationships
Class Diagrams: An Agile Introduction
Difference between association, aggregation and composition
Association vs. Dependency vs. Aggregation vs. Composition

你可能感兴趣的:(设计模式始记——五分钟学UML)