关闭

话说Association, Composition, Aggregration and Dependancy的区别

标签: classstring
212人阅读 评论(0) 收藏 举报
分类:

Association一般是表示两个class/object之间的关系,如:

// Foo has an association with Bar
public class Foo {
    public void doSomething() {
        System.out.println(Bar.doSomethingElse());
    }
}
// Utils has an association with Message
public class Utils {
    public static void print(Message msg) {
        System.out.println(msg.toString());
    }
}
// Message has an association with Person,准确的来说应该是Aggregration的关系
public class Message {
    private Person recipient;
    private Person sender;
    private String text;
    public Message(Person recipient, Person sender, String text) {
        this.recipient = recipient;
        this.sender = sender;
        this.text = text;
    }
}
Composed:
   1: // WebServer is composed of a HttpListener and a RequestProcessor
   2: public class WebServer {
   3:     private HttpListener listener;
   4:     private RequestProcessor processor;
   5:     public WebServer(HttpListener listener, RequestProcessor processor) {
   6:         this.listener = listener;
   7:         this.processor = processor;
   8:     }
   9: }
   1: // WebServer is an aggregate of HttpListener and RequestProcessor
   2: // and controls their lifecycle
   3: public class WebServer {
   4:     private HttpListener listener;
   5:     private RequestProcessor processor;
   6:     public WebServer() {
   7:         this.listener = new HttpListener(80);
   8:         this.processor = new RequestProcessor("/www/root");
   9:     }
  10: }

说说我的理解吧:

Association表示两个类之间的关系,通常表示为一个类对另一类的引用;

Composition表示该类需要另一个类且管理那个类的生命周期,并且一般该类由引用的类来创建;

Aggregration通常由构造方法传入另一个对象或通过依赖注入;

Dependancy通常是通过方法的参数或静态类的引用。

如果我讲的不对,请指正我的说法,谢谢!

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:26822次
    • 积分:559
    • 等级:
    • 排名:千里之外
    • 原创:31篇
    • 转载:1篇
    • 译文:0篇
    • 评论:3条
    文章分类
    博客友情链接