The relationship and representation between classes in UML class diagram (Class Diagram)

There are five types of relationships between classes:

 

1. Dependency

One-way , which means that a class depends on the definition of another class, and changes in one class will affect the other class, which is a " use a " relationship

If A depends on B, then B behaves as A's local variables, method parameters, static method calls, etc.

[java]  view plain copy  
 
  1. publicclass Person {   
  2.     publicvoid doSomething(){   
  3.         Card card =  new  Card(); //local variable  
  4.         ....  
  5.     }  
  6. }  
[java]  view plain copy  
 
  1. publicclass Person {   
  2.     public void  doSomething(Card card){ //Method parameters   
  3.         ....  
  4.     }  
  5. }  
[java]  view plain copy  
 
  1. publicclass Person {   
  2.     publicvoid doSomething(){   
  3.         int  id = Card.getId(); // static method call  
  4.         ...  
  5.     }  
  6. }  

 

2. Association

One-way or two-way (usually we need to avoid using two-way association relationship), is a " has a " relationship, if A is unidirectionally related to B, then it can be said that A has a B, usually expressed as a global variable

[java]  view plain copy  
 
  1. publicclass Person {   
  2.     public Phone phone;  
  3.       
  4.     public void setPhone(Phone phone){        
  5.         this.phone = phone;  
  6.     }  
  7.       
  8.     public Phone getPhone(){          
  9.         return phone;  
  10.     }  
  11. }  

 

3,聚合关系(Aggregation)

单向,关联关系的一种,与关联关系之间的区别是语义上的,关联的两个对象通常是平等的,聚合则一般不平等,有一种整体和局部的感觉,实现上区别不大

Class由Student组成,其生命周期不同,整体不存在了,部分依然存在,当前Team解散了,人还在,还可以加入别的组

[java]  view plain  copy
 
  1. public class Team {  
  2.     public Person person;  
  3.       
  4.     public Team(Person person){  
  5.         this.person = person;  
  6.     }  
  7. }  

 

4,组合关系(Composition)

单向,是一种强依赖的特殊聚合关系

Head,Body,Arm和Leg组合成People,其生命周期相同,如果整体不存在了,部分也将消亡

[java]  view plain  copy
 
  1. public class Person {  
  2.     public Head head;  
  3.     public Body body;  
  4.     public Arm arm;  
  5.     public Leg leg;  
  6.       
  7.     public Person(){  
  8.         head = new Head();  
  9.         body = new Body();  
  10.         arm = new Arm();  
  11.         leg = new Leg();  
  12.     }  
  13. }  

 

5. Inheritance

A class implements an interface, a class inherits an abstract class, and a class inherits from a parent class belongs to this relationship

It can be divided into finer points:

Realization: A class implementing an interface belongs to this relationship

Generalization: that is, the " is a " relationship, the class inherits the abstract class, and the class inherits the parent class belongs to this relationship

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325339672&siteId=291194637