聚集,关联和组成 [英] Aggregation, Association and Composition

查看:61
本文介绍了聚集,关联和组成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的例子:

public class Order 
{

 private ArrayList<Product> orders = new ArrayList<Product>();

 public void add(Product p)
 {
  orders.add(p);
 }
}

是聚集还是组成?我想它是组成文件,因为删除订单后订单将被延迟,对吗?不幸的是,这是一项任务,答案却有所不同;/您知道为什么吗?

Is it aggregation or composition? I guess it's composition, because orders will be delated after delete of Order, right? Unfortunately it was a task and answer was different;/ Do you know why?

第二个问题:

public class Client extends Person 
{
    String adress = "";

    Orders orders = new Orders();

    public Client(String n, String sn)
    {
     name = n;
     surName = sn;
    }

    public String getAddress()
    {
     return adress;
    }
    public Orders getOrders()
    {
     return this.orders; 
    }
}

客户与订单之间是否存在关联?我的老师告诉我这是关联,但是我想知道为什么它不是聚合/组合-他告诉我,只有当一个类包含几个不同类的实例时才会发生聚合或组合-是吗?我猜不是,因为我猜汽车包含一个车轮及其集合体吗?

Is it Association between Client and Orders? My teacher told me that this is association, but I was wondering why it's not a aggregation/composition - he told me that aggregation or composition occur only when one class contains few instances of different class - is that right? I guess not, because e.g. car contains ONE wheel and its aggregation I guess?

那是什么类型的关系,为什么?

What type of relation is that and why?

推荐答案

第一个示例是聚合.删除Order实例时,可能会删除变量 orders ,但是每个Product仍然具有含义,并且可以存在于Order类之外.

Your first example is aggregation. The variable orders might be deleted when the Order instance is deleted, but each Product still has meaning and can exist outside the Order class.

您在第二个示例中是对的.因为客户端包含对订单的(has-a)引用,所以这是一种组合(因为没有 Client 的情况下 orders 不存在).

You're right in your second example. Because Client contains a (has-a) reference to Orders, this is composition (because orders doesn't exist without a Client).

聚集和组合都是不同的关联类型,但是它们是特定的关联类型.为了使两个类仅具有关联而没有聚集或组合,它们需要比给出的示例更弱的链接.这是一个(人为的)示例:

Aggregation and composition are both different types of association, but they're specific types of association. In order for two classes to have just an association without aggregation or composition, they need a weaker link than the example given. Here's a (contrived) example:

class A {
    String phrase = "These pretzels are making me thirsty.";

    public String process(B b) {
        // use a B object to do something
        String tmp = b.doSomething(phrase);

        // do more processing...
        return tmp;
    }
}

class B {
    public String doSomething(String s) {
        // do something with the input string and return
        ...
    }
}

这里没有组成或聚合(A没有对B对象的自身引用),但是由于B的实例由A中的方法使用,因此存在关联.

Here there is no composition or aggregation (A does not have it's own reference to a B object), but since an instance of B is used by a method in A, there is an association.

这篇关于聚集,关联和组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆