我是耦合和凝聚概念的新手。给定的是一个显然包含两个不同概念的类的代码。我怎样才能让它更具凝聚力?把它分成两类?那么这些课程将如何沟通?
class order {
public:
int getOrderID();
date getOrderDate();
float getTotalPrice();
int getCustometId();
string getCustomerName();
string getCustometAddress();
int getCustometPhone();
void setOrderID(int oId);
void setOrderDate(date oDate);
void setTotalPrice(float tPrice);
void setCustometId(int cId);
void setCustomerName(string cName);
void setCustometAddress(string cAddress);
void setCustometPhone(int cPhone);
void setCustomerFax(int cFax)
private:
int oredrId;
date orderDate;
float totalPrice;
item lineItems[20];
int customerId;
string customerName;
int customerPhone;
int customerFax;
现在,如果我创建了两个类Order
和customer
,那么customerID
类中的Order
是否包含在其私有属性中?或者只是将它分成两个不相交的类?下订单时order
类如何设置customerID
?
答案 0 :(得分:3)
如果这是针对数据库应用程序的,则所有order
需求都是customer
ID,所有客户需求都是order
ID。查询数据时,只需交叉引用ID即可。除非您希望信息紧密耦合,否则order
无法存储客户信息,反之亦然。
void createOrder() {
Order order;
order.customer_id = this->id;
// something with database
}
customer.createOrder();
然后,您可以通过这种方式获取特定客户的所有order
。
SELECT * FROM orders WHERE customer_id = ...
答案 1 :(得分:1)
如果是我,客户和订单将是两个不同的实体。此外,由于客户可以拥有多个订单,我会收到一些订单。
这样的事情:
class Customer; // Forward declaration of the `Customer` class
// So it can be used by the `Order` class
class Order
{
public:
Order(Customer* c)
: customer(c)
{}
// Other public functions...
private:
// Other order specific data...
Customer* customer; // Customer for this order
};
class Customer
{
public:
...
private:
// Other customer data...
std::vector<Order> orders; // Collection of order for this customer
};
然后,您只需为单个客户创建新订单,方法是将其添加到order
集合中:
void Customer::add_order()
{
orders.push_back(Order(this))
}
答案 2 :(得分:0)
将课程分为&#39;顺序&#39;课程和&#39;客户&#39;类。 (尝试遵循命名约定)
将Customer对象的引用保留为Order的属性。
您可以进一步将其划分为CustomerInfo和OrderInfo等类,以便将来更容易扩展功能。 (低耦合)
阅读这些内容以供进一步探索
http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)
http://en.wikipedia.org/wiki/Separation_of_concerns