`

类之间的关系2

    博客分类:
  • C++
阅读更多
  继承,这没什么好说的了。

  依赖(Dependency):依赖是使用关系。它指的是改变被使用者会接影响使用者,而改变使用者则不一定影响被使用者的关系。原文:  
  “A   Dependency   is   a   using   relationship   that   states   that   a   change   in   specification   of   one   thing   may   affect   another   thing   that   uses   it,   but   not   necessariyly   the   reverse”。  
  例如,人因驾车这一动作而产生的人和车的关系是Dependency关系。不同种类的车,驾驶的方法可能不一样。但不同种类的人不一定会用不同的方法驾车。  
    
   
  关联(Association):这是个包含面较广的较为模糊的关系,实质上是use-a的关系。请看原文: “An   association   is   a   structure   relationship   that   specifies   that   objects   of   one   thing   are   connected   to   objects   of   another”。  
  你需要对此作更多的说明来体现具体的关系。比如:“房子里住了人”所表示的房子和人的关系。“公司雇用人”包含的公司和人的关系。  
   
  聚集(Aggregation):这是Association的一种。它实质上是has_a的关系。它可用来表示整体和个体的关系。比如:公司和部门,汽车和轮胎,家庭和人等。  
   
  我认为use_a和has_a绝对。use_a只是用到,在C++可能是函数的参数,也可能是全局变量,或singleton等。人打电话时要用电话。这时人和电话的关系是use_a。用到的电话可能是你自己的,借别人的,公司的,或公用的。其实质是打(use)电话不一定要有(has)自己的电话。你可以用has_a来实现use_a因为只要有当然总可以用。但是这use_a被缩小成“总是用自己的”。它其实还是has_a不是use_a(不要只站在这一动作的角度来看,要站在类的角度来看因为这是在谈类之间的关系)。


举例:
1,继承(Inheritance)  
  X   is_a   Y  
   
  class   Y  
  {  
  };  
  class   X   :   public   Y  
  {  
  };
 
  2,聚集(Aggregation)  
  B   has_a   C  
  //C   and   B   is   an   unidirectional   aggregation   relationship,B   owns   C;  
  class   C  
  {  
  };  
   
  class   B  
  {  
  C   myC;  
  };  
  //Aggregation   with   multiplicty   of   10  
  class   A  
  {  
  };  
  class   B  
  {  
  A   tempA[10];  
  };  
  //Aggregation   with   multiplicty   of   0   or   more   using   vector   container  
  class   A  
  {  
  };  
   
  class   B  
  {  
  vector<A>   myAs;  
  }; 

  3,依赖(Dependency)  
  Dependencies   are   very   weak   relationships   between   2   classes  
  so   weak   that   they   are   not   implemented   as   varibles   but   often   implemented   as   parameters   for   methods   ,you   see   this   alot   in   COM  
  A   depends   on   B  
  class   B  
  {  
  };  
   
  class   A  
  {  
  bool   INeedToDoSomething(B   aB);  
  }  
   
  4,关联(Association)  
  Assocation  
  //T   Assocates   with   S  
  class   S  
  {  
  };  
  class   T  
  {  
  S*   theS;  
  };  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics