【发布时间】:2014-07-14 10:22:54
【问题描述】:
在一个项目中,我有以下类关系。 Employee 和 Client 与 Company 具有组合关系。所以实现如下。
class Company
{
private Employee _Employee {get;set;} // private fields as composition
private Client _Client {get;set;}
public Company()
{
_Employee = new Employee();
_Client = new Client();
}
public AddEmploees() //Employee objects are controlled by Company
{
//
}
public DeleteEmploees()
{
//
}
public AddClients() //Client objects are controlled by Company
{
//
}
public DeleteClients()
{
//
}
}
class Employee
{
string Name {get;set;}
int ID {get;set;}
string Address {get;set;}
string Department {get;set;}
DateTime DOB {get;set;}
private Employee() // constructor private
{
}
}
class Client
{
string CID {get;set;}
string Name {get;set;}
string Type {get;set;}
DateTime StartDate {get;set;}
string Address {get;set;}
private Client() // constructor private
{
}
}
当我想在 UI 上显示 client / employee 详细信息时,我的 DataService 应该返回 Company 对象,而不是返回 Employee/Client 对象,因为关系是组合。所以我可以在我的DataService 中有一个类似GetDetails() 的方法,然后从数据库中获取所需的详细信息以分配Employee 和Client 的属性。但现在的问题是,我将无法访问 Company 对象的私有字段(_Employee、_Client)来设置属性值,如下所示
public Company GetDetails()
{
Company company = new Company();
string selectStatement = "SELECT...";
// Get data from DB
company.client.name = rdr["name"].value; // This is not possible.
.
.
.
}
虽然我几乎没有解决这个问题的想法,但它们似乎都不适合这种类关系(组合)或违反关注点分离原则。感谢您在这方面的帮助?
【问题讨论】:
-
为什么这不可能?
-
因为包含的类 Company 的 Client 属性是私有的。
-
要么创建一个公共属性来包装它
public Client Client { get { return _client; } },要么你有一个公共方法来访问各个属性GetClientName/SetClientName。在我看来,SoC 与这种设计无关。您相当受 SOLID 原则的约束,这并不违反任何这些规则。
标签: c# .net uml mvp composition