C# UML类图

UML类图有关联、聚合/组合、依赖、泛化(继承,实现)这样几种关系。


事实上关联、聚合/组合这几种关系很容易搞混。比如图1.1在PowerDesigner中生成的代码都是一样的。


图1.1

而什么时候使用关联,聚合/组合呢?
1、关联
当Class_A与Class_B有一种关系时使用,比如父子关系。
2、聚合/组合
当Class_A与Class_B有包含关系,是has a的情况使用。具体看如果Class_A包含Class_B,而Class_A知道Class_B的生命周期,那就用组合;如果有包含关系却不知道生命周期,那就用聚合。
图1.2
如图1.2,父亲(Father)让儿子(Son)去做一些事情,这就是关联。而人(Person)有一个脑袋(Head),人死了,脑袋自然没用了,这就用组合。电脑(Computer)有条内存,现在电脑坏掉了,但是内存还能用,这就是聚合。反映成代码就是:
1、关联
public class Son
{
    
public void DoSomething()
    {
    }
}

public class Father
{
   
public Son son;

    
public Father(Son son)
    {
        
this.son = son;
    }

    
public void LetSonTodo()
    {
        son.DoSomething();
    }
}
2、组合

public class Head
{
    
public void Think()
    {
    }
}

public class Person
{
   
public Head head;

    
public Person()
    {
        head 
= new Head();
    }

    
public void Think()
    {
        head.Think();
    }
}

3、聚合

 

public class Memory
{
}

public class Computer
{
   
public Memory memory;

    
public Computer(Memory memory)
    {
        
this.memory = memory;
    }
}

 

在C#中依赖也有特点。我认为依赖的代码应该是这样:

public class Official
{
    
private bool effort;

    
public bool Effort
    {
        
get { return effort; }
        
set { effort = value; }
    }
}

public class Boss
{
    
public void Work(Official official)
    {
        
if (official.Effort)
        {
            
//产生的结果
        }
        
else
        {
            
//另外的结果
        }
    }
}

 

至于泛化(继承、实现)这个是最简单的,是is a的关系。就不多说了。

posted on 2009-08-01 11:40  yurow  阅读(2593)  评论(0编辑  收藏  举报

导航