UML类图详解_关联关系_一对多

对于一对多的示例,可以想象一个账户可以多次申购。在申购的时候没有固定上限,下限为0,那么就可以使用容器类(container class)来搞,最常见的就是vector了。

下面我们来看一个“一对多”的例子

Account.h

 1 #include <cstdlib>
 2 #include <vector> 
 3 #include "Bid.h"
 4 using namespace std;
 5  
 6 class Account 
 7 {
 8 public:
 9     void setBid(Bid*); 
10     int calcAmount(); 
11 private:
12     vector<Bid*> bidObj;
13 };

声明一个存放申购交易对于指针的vector对象。然后类Account中的函数setBid设计了一个公有操作,让外界用来传入申购交易对象的指针,以便让账户对象将申购交易对象指针存入vector对象中。

Account.cpp

 1 #include "Account.h"
 2             
 3 void Account::setBid(Bid *theBid)
 4 { 
 5      bidObj.push_back(theBid);
 6 }
 7 
 8 int Account::calcAmount()
 9 {
10      int size,theAmount=0;
11      size=bidObj.size();
12      for(int i=0;i<size;i++)
13          theAmount=theAmount+bidObj[i]->getAmount();
14      return theAmount; 
15 } 

Bid.h

1 class Bid 
2 {
3 public:
4     void setAmount(int); 
5     int getAmount();
6 private:
7     int amount;
8 };

Bid.cpp

 1 #include "Bid.h"
 2 
 3 void Bid::setAmount(int theAmount)
 4 { 
 5      amount=theAmount;
 6 }
 7  
 8 int Bid::getAmount()
 9 {
10     return amount;
11 }

main.cpp

 1 #include <cstdlib>
 2 #include <iostream>
 3 #include "Bid.h"
 4 #include "Account.h" 
 5 using namespace std; 
 6  
 7 int main(int argc, char *argv[])
 8 { 
 9     Bid *myBid; 
10     Account myAccount; 
11     int theAmount;
12     int choice;
13     
14     do
15     {
16         cout << "请输入申购金额: ";
17         cin >> theAmount;
18         myBid=new Bid;        
19         myBid->setAmount(theAmount); 
20         myAccount.setBid(myBid); 
21         cout << "1(继续), 2(结算) ...";
22         cin  >> choice;
23         cout << endl;
24     } while(choice==1); 
25       
26     cout << "总投资金额为: "
27          << myAccount.calcAmount() << endl << endl; 
28          
29     system("PAUSE");
30     return EXIT_SUCCESS;
31 }

下面我们来画一下UML图,并且用UML自动生成C++代码来做一个比较

画法一:

生成代码对比

Account.h

没有达到预期,多生成了成员变量,如果在类图里面写明了某个指针变量的话,那么在关联关系的端点处就不能再标示这个成员变量了,否则就会重复生成

UML类图详解_关联关系_多对一中的画法二,也是因为这个导致了没有达到预期

Bid.h

达到预期

画法二:

生成代码对比

Account.h

达到预期

Bid.h

达到预期

画法三:

生成代码对比

Account.h

没有达到预期

Bid.h

达到预期

综上所述,在实际画图的时候采用画法二才能保证正确,一旦类图里面包含了一次成员那么在关联端点再声明一次的话就会重复,另外如果不在类图里面包含一次成员而在关联端点处声明一次的话生成的代码比较傻,很多情况下无法满足我们的要求。所以我们就是把成员都在类图里面包含进去,关联端点处就是声明一下多重性,而不要再声明成员就可以了。 

原文地址:https://www.cnblogs.com/abc-begin/p/7749738.html