1. 程式人生 > >UML 類圖總結

UML 類圖總結

log iat face div 語言 返回 ddr -c gre

類的表示

技術分享圖片

從上到下:類名、屬性、方法、內部類

若類名為斜體則表示其為虛類

標示符前的符號含義如下:
符號|含義
-|-
+|public
-|private
#|protected

標示符的冒號後表示:屬性類型或返回類型

類間關系

關聯 Association

技術分享圖片

在使用Java、C#和C++等編程語言實現關聯關系時,通常將一個類的對象作為另一個類的成員變量。

class LoginForm {  
    private JButton loginButton; //定義為成員變量  
}  
class JButton {}

雙向關聯

技術分享圖片

public class Customer {  
    private
Product[] products; } public class Product { private Customer customer; }

單向關聯

技術分享圖片

public class Customer {  
    private Address address;  
}  
public class Address {}  

自關聯

技術分享圖片

public class Node {  
    private Node subNode;  
}  

多重性關聯

技術分享圖片

public class Form {  
    private Button[] buttons; //定義一個集合對象  
} public class Button {}

聚合 Aggregation

技術分享圖片

在聚合關系中,成員對象是整體對象的一部分,但是成員對象可以脫離整體對象獨立存在。

成員對象通常作為構造方法、Setter方法或業務方法的參數註入到整體對象中。

public class Car {  
    private Engine engine;  
  
    public Car(Engine engine) {  
        this.engine = engine;  
    }  
      
    public void setEngine(Engine engine) {  
        this
.engine = engine; } } public class Engine {}

組合 Composition

技術分享圖片

組合關系中整體對象可以控制成員對象的生命周期,一旦整體對象不存在,成員對象也將不存在,成員對象與整體對象之間具有同生共死的關系。

在整體類的構造方法中直接實例化成員類。

public class Head {  
    private Mouth mouth;  
  
    public Head() {  
        mouth = new Mouth(); //實例化成員類  
    }  
}  
public class Mouth {}  

依賴 Dependency

技術分享圖片

一種使用關系,特定事物的改變有可能會影響到使用該事物的其他事物,在需要表示一個事物使用另一個事物時使用依賴關系。

將一個類的對象作為另一個類中方法的參數

class Driver {
    public drive(Car car) {
        car.move();
    }
}

class Car {
    public void move();
}

在一個類的方法中將另一個類的對象作為其局部變量

Class Main {
    pubilc static void main(String[] args) {
        File file = new File(args[0]);
        Scanner scanner = new Scanner(file);
        ...
    }
}

在一個類的方法中調用另一個類的靜態方法

Class Main {
    pubilc static void main(String[] args) {
        System.out.println("hello");
    }
}

泛化 Generalization

即繼承關系。
技術分享圖片

//父類  
public class Person {  
    protected String name;  
    protected int age;  
  
    public void move() {} 
    public void say() {}  
}  
  
public class Student extends Person {  
    private String studentNo;  
  
    public void study() {}  
}  
  
public class Teacher extends Person {  
    private String teacherNo;  
  
    public void teach() {}  
}  

實現 Realization

技術分享圖片

public interface Vehicle {  
    public void move();  
}  
  
public class Ship implements Vehicle {  
    public void move() {}  
}  
  
public class Car implements Vehicle {  
    public void move() {}
}

UML 類圖總結