想要学习设计模式,你得先会看类图,一张图读懂UML

Explanation of the UML arrows

https://www.cnblogs.com/chucklu/p/10623671.html

 

想要学习设计模式,你得先会看类图,一张图读懂UML

虚线箭头指向依赖dependency;

实线箭头指向关联associate;

虚线三角指向接口;

实线三角指向父类;

空心菱形能分离而独立存在,是聚合aggregation;

实心菱形精密关联不可分,是组合composition;

虚箭依,实箭关

虚三接,实三父

空菱聚,实菱组

Aggregation vs Composition

Simple rules:

  1. A "owns" B = Composition : B has no meaning or purpose in the system without A
  2. A "uses" B = Aggregation : B exists independently (conceptually) from A

Example 1:

A Company is an aggregation of People. A Company is a composition of Accounts. When a Company ceases to do business its Accounts cease to exist but its People continue to exist.

Example 2: (very simplified)

A Text Editor owns a Buffer (composition). A Text Editor uses a File (aggregation). When the Text Editor is closed, the Buffer is destroyed but the File itself is not destroyed.

So is a car an aggregate or a composition of its parts?

@reinierpost In reality, a car is an aggregation of parts, and parts are simply an aggregation of molecules分子... However, in a model it all depends on your requirements. Is it important to treat the engine as a separate entity so that you can track its lifetime independent of the car? Can you reuse the exact same engine in another car? If so, then you probably want aggregation. Otherwise you want a composition because you don't care about engines that aren't part of cars, nor do you care about reusing engines.

Difference between association and dependency?

回答1

 

An association almost always implies that one object has the other object as a field/property/attribute (terminology differs).

A dependency typically (but not always) implies that an object accepts another object as a method parameter, instantiates, or uses another object. A dependency is very much implied by an association

回答2

 

In OOP terms:

Association --> A has-a C object (as a member variable)

Dependency --> A references B (as a method parameter or return type)

public class A {
    private C c;
    public void myMethod(B b) {
        b.callMethod();
    }
}

There is also a more detailed answer.

原文地址:https://www.cnblogs.com/chucklu/p/12889603.html