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

2022-12-01,,

首先先来明确一个概念,即多重性。什么是多重性呢?多重性是指两个对象之间的链接数目,表示法是“下限...上限”,最小数据为零(0),最大数目为没有设限(*),如果仅标示一个数目级上下限相同。

实际在UML中是可以隐藏上图中申购交易的细节

导航性(navigation):关联关系的细节信息通常放置于两关联端,像是关联端标示箭头,代表该关联端具有可导航性。

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

Fund.h

 class Fund
{
public:
void setPrice(float);
float getPrice();
void setFee(float);
float getFee();
private:
float price;
float fee;
};

Fund.cpp

 #include "Fund.h"

 void Fund::setPrice(float thePrice)
{
price=thePrice;
} float Fund::getPrice()
{
return price;
} void Fund::setFee(float theFee)
{
fee=theFee;
} float Fund::getFee()
{
return fee;
}

Bid.h

 #include "Fund.h"

 class Bid
{
public:
float calcUnit();
float calcFee();
void setFund(Fund*);
void setAmount(int);
int getAmount();
private:
int amount;
Fund *fundObj;
};

声明一个基金对象指针,此即为多重性为1的实现方法之一。然后类Bid中的函数setFund设计了一个公有操作,让外界可以传入基金对象的指针,也就建立起申购交易对象指向基金对象的链接了。

Bid.cpp

 #include "Bid.h"

 float Bid::calcUnit()
{
float thePrice, theUnit;
thePrice=fundObj->getPrice();
theUnit=amount/thePrice;
return theUnit;
} float Bid::calcFee()
{
float theFundFee, theFee;
theFundFee=fundObj->getFee();
theFee=amount*theFundFee;
return theFee;
} void Bid::setFund(Fund *theFund)
{
fundObj=theFund;
} void Bid::setAmount(int theAmount)
{
amount=theAmount;
} int Bid::getAmount()
{
return amount;
}

main.cpp

 #include <cstdlib>
#include <iostream>
#include "Fund.h"
#include "Bid.h"
using namespace std; int main(int argc, char *argv[])
{
Fund myFund;
float thePrice, theFee;
Bid myBid;
int theAmount; cout << "请输入大华大华基金净值: ";
cin >> thePrice;
myFund.setPrice(thePrice);
cout << "请输入大华大华基金手续费: ";
cin >> theFee;
myFund.setFee(theFee); cout << "请输入申购金额: ";
cin >> theAmount;
myBid.setAmount(theAmount);
myBid.setFund(&myFund); cout << "您申购的单位及手续费为: "
<< "(" << myBid.calcUnit() << ")"
<< "(" << myBid.calcFee() << ")" << endl << endl; system("PAUSE");
return EXIT_SUCCESS;
}

通过调用myBid.setFund(&myFund)将基金对象的指针传给申购交易对象,于是就建立起申购交易对象指向基金对象的链接。

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

画法一:

生成代码对比

Bid.h

达到预期

Fund.h

达到预期

画法二:

生成代码对比

Bid.h

没有达到预期,重复生成了成员变量

Fund.h

达到预期

画法三:

生成代码对比

Bid.h

达到预期

Fund.h

达到预期

综上所述,在实际画图的时候采用画法一或者画法三都可以,个人还是觉得画法一好一些   (update 2017-10-29)其实应该是使用画法一,这样可以避免错误,具体错误的例子可以见UML类图详解_关联关系_一对多,一旦有了比较复杂的类型,那么生成的代码就不靠谱了。一旦类图里面包含了一次成员那么在关联端点再声明一次的话就会重复,另外如果不在类图里面包含一次成员而在关联端点处声明一次的话生成的代码比较傻,很多情况下无法满足我们的要求。所以我们就是把成员都在类图里面包含进去,关联端点处就是声明一下多重性,而不要再声明成员就可以了。

UML类图详解_关联关系_多对一的相关教程结束。

《UML类图详解_关联关系_多对一.doc》

下载本文的Word格式文档,以方便收藏与打印。