在關聯關系中,很多情況下我們的多重性並不是多對一或者一對多的,而是多對多的。
不過因為我們要考慮里面的導航性,如果直接搞的話就是需要去維護兩群對象之間多對多的互指鏈接,這就十分繁雜且易錯。那么我們怎么辦呢?可以將多對多的多重性嘗試拆解為兩組一對多的設計。
我們可以改為上圖的這種拆解方法。就是說在賬戶與基金之間多搞一個申購交易,這樣就可以化解多對多的復雜度。一個賬戶底下可以記錄多筆申購交易,而每一個申購交易將指定某一檔基金。雖然可以重復申購同一檔基金,不過每一個申購交易只能設定一檔基金。
一個賬戶對象可以鏈接多個申購交易對象,而每個申購交易對象只能鏈接到一個基金對象。
下面我們來看一個“多對多”的例子
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 calcAsset(); 11 private: 12 vector<Bid*> bidObj; 13 };
Account.cpp
1 #include "Account.h" 2 3 void Account::setBid(Bid *theBid) 4 { 5 bidObj.push_back(theBid); 6 } 7 8 int Account::calcAsset() 9 { 10 int size,theAsset=0; 11 size=bidObj.size(); 12 for(int i=0;i<size;i++) 13 theAsset=theAsset+bidObj[i]->calcAsset(); 14 return theAsset; 15 }
Bid.h
1 #include "Fund.h" 2 3 class Bid 4 { 5 public: 6 Bid(float); 7 void setFund(Fund*); 8 int calcAsset(); 9 float getUnit(); 10 private: 11 float unit; 12 Fund *fundObj; 13 };
Bid.cpp
1 #include "Bid.h" 2 3 Bid::Bid(float theUnit) 4 { 5 unit=theUnit; 6 } 7 8 void Bid::setFund(Fund *theFund) 9 { 10 fundObj=theFund; 11 } 12 13 int Bid::calcAsset() 14 { 15 return unit*fundObj->getPrice(); 16 } 17 18 float Bid::getUnit() 19 { 20 return unit; 21 }
Fund.h
1 class Fund 2 { 3 public: 4 Fund(float); 5 float getPrice(); 6 private: 7 float price; 8 };
Fund.cpp
1 #include "Fund.h" 2 3 Fund::Fund(float thePrice) 4 { 5 price=thePrice; 6 } 7 8 float Fund::getPrice() 9 { 10 return price; 11 }
main.cpp
1 #include <cstdlib> 2 #include <iostream> 3 #include "Bid.h" 4 #include "Account.h" 5 #include "Fund.h" 6 using namespace std; 7 8 int main(int argc, char *argv[]) 9 { 10 Fund *myFund; 11 Bid *myBid; 12 Account myAccount; 13 14 myFund=new Fund(19.84); 15 myBid=new Bid(100); 16 myBid->setFund(myFund); 17 myAccount.setBid(myBid); 18 cout << "大華大華基金單位及凈值: " 19 << "(" << myBid->getUnit() << ")" 20 << "(" << myFund->getPrice() << ")" << endl; 21 22 myFund=new Fund(37.83); 23 myBid=new Bid(200); 24 myBid->setFund(myFund); 25 myAccount.setBid(myBid); 26 cout << "日盛上選基金單位及凈值: " 27 << "(" << myBid->getUnit() << ")" 28 << "(" << myFund->getPrice() << ")" << endl; 29 30 myBid=new Bid(300); 31 myBid->setFund(myFund); 32 myAccount.setBid(myBid); 33 cout << "日盛上選基金單位及凈值: " 34 << "(" << myBid->getUnit() << ")" 35 << "(" << myFund->getPrice() << ")" << endl << endl; 36 37 cout << "總資產為: " 38 << myAccount.calcAsset() << endl << endl; 39 40 system("PAUSE"); 41 return EXIT_SUCCESS; 42 }
下面我們來畫一下UML圖,並且用UML自動生成C++代碼來做一個比較
生成代碼對比
Account.h
達到預期
Bid.h
達到預期
Fund.h
達到預期