[转]association,aggregation, composition 区别

来源:互联网 发布:rush鼻吸器淘宝 编辑:程序博客网 时间:2024/05/08 00:39

 

三者从概念上来讲:Association是一般的关联,有”user a”的含义。Aggregation和Composition都有整体和部分的关系,其中Aggregation中的部分脱离了整体,部分仍然有意义,有”has a”的含义,是共享式的。而Composition中的部分脱离了整体,部分将没有任何意义,是独占式的。
  从实现的角度上讲:三者都是以属性出现,其中Association中作为属性出现时,不需要对其进行强制赋值,只要在使用是对其进行初始化即可。Aggregation中作为属性出现时,需要在构造器中通过传递参数来对其进行初始化。Composition中  作为属性出现时,需要在整体的构造器中创建部分的具体实例,完成对其的实例化。
  从的层面上来讲:Association不需要被级联删除,Aggregation不需要被级联删除,Composition是需要被级联删除的。
  下面通过一个例子来更深刻的理解这三者的区别。
//Association relationship
public class Student{
private String name;
private int age;
BasketBall aBall;
public Student( String name, int age){
   this.name=name;
   this.age=age;
}
public void getBall(BasketBall aBall){
    this.aBall=aBall;
}
public void play(){
  System.out.println("I am playing basketball"+aBall);
}
}

class BasketBall{
private Color aColor;
private int size;
public BasketBall(Color aColor, int size){
   this.aColor=aColor;
   this.size=size;
}
}  

class StudentAdmin{
public static void main(String aa[]){
   Student aStudent=new Student("Peter", 22);
   BasketBall aBasketBall=new BasketBall(Color.red, 32);
   aStudent.getBall(aBasketBall);
   aStudent.play();
}
}

//Aggregation relationship

public class Computer{
private String cpu;
private float weight;
private Monitor aMonitor;
public Computer(String cpu, float weight, Monitor aMonitor){
   this.cpu=cpu;
   this.weight=weight;
   this.aMonitor=aMonitor;
}
public void turnOn(){    System.out.println("I am on now");  }
}
class Monitor{
private int inch;
private boolean isFlat;
//no information of computer
public Monitor(int inch, boolean isFlat){
   this.inch=inch;
   this.isFlat=isFlat;
}
}
class ComputerAdmin{
public static void main(String aa[]){
   Monitor aMonitor=new Monitor(17, true);  
   System.out.println("I do something others here");
   Computer aComputer=new Computer(486, 32.0, aMonitor);
   System.out.println("Computer is :"+aComputer);
   aComputer.turnOn();
}
}

//Composition
public class Computer{
private String cpu;
private float weight;
private Monitor aMonitor;
public Computer(String cpu, float weight, int inch, boolean isFlat){
   this.cpu=cpu;
   this.weight=weight;
   this.aMonitor=new Monitor(inch, isFlat);
}
public void turnOn(){    System.out.println("I am on now");  }
}
class Monitor{
private int inch;
private boolean isFlat;
//no information of computer
public Monitor(int inch, boolean isFlat){
   this.inch=inch;
   this.isFlat=isFlat;
}
}
class ComputerAdmin{
public static void main(String aa[]){
   //Monitor aMonitor=new Monitor(17, true);  
   Computer aComputer=new Computer(486, 32.0, 17, true);
   System.out.println("Computer is :"+aComputer);
   aComputer.turnOn();
}
}