4

如果我将我的对象分解为“单一职责”,是否有一个基本的想法是类似的对象应该一起存在还是分开存在,例如,如果我有

class Employee_DataProvider() : IEmployee_DataProvider { ... };
class Employee_Details() : IEmployee_Details { ... };
class Employee_Payroll() : IPayroll() { ... };
class Employee_LeaveProcessing() : ILeaveProcessing_Client { ... };
...

将所有这些都存在于内部,但通过接口松散耦合到一个拥有的 Employee 类,是不是很糟糕:

class Employee
{
    IEmployee_DataProvider _dataProvider;
    IEmployee_Details _details;
    IPayroll _payroll;
    ILeaveProcessing_Client _leaveProcessing;

    //My functions call the interfaces above

}

还是更多地考虑在代码中将这些类完全分开(或尽可能地分开)?或者这两种方法都是 SRP 的有效用法?

编辑:我不想批评示例中给出的对象的可行性,我只是为了说明问题而编造出来的。我同意数据、休假和工资单处理不是员工类的领域。

尽管 SRP 确实要求我从作为现实世界表示的对象转向作为围绕单个功能概念的属性和方法的对象

4

2 回答 2

4

回到 OOP 的基础知识:Employee 对象应该有反映它所做的事情的方法,而不是对它做了什么。

于 2009-01-17T02:41:42.110 回答
2

尽管还没有人解决我关于原则本身的实际问题,而不是我给出的有点糟糕的例子,一个 Employee 对象对影响它的过程了解太多,对于那些显然对这个问题感兴趣的人(有 2 '最喜欢的'星)我已经做了更多的进一步阅读,尽管我希望有更多的讨论。

I think what the two current answers are trying to say is that responsibilities separated should be able to be stand alone, and that my example was a perfect example of what not to do. I am more than happy to accept that.

There is a paragraph from ObjectMentor (Uncle Bob's site) that has an example that combines Connection and DataReader objects (two objects previously living in a modem class then separated out) into a ModemImplementation, but states

However, notice that I have recoupled the two responsibilities into a single ModemImplementation class. This is not desirable, but it may be necessary. There are often reasons, having to do with the details of the hardware or OS, that force us to couple things that we’d rather not couple. However, by separating their interfaces we have decoupled the concepts as far as the rest of the application is concerned.

We may view the ModemImplementation class is a kludge, or a wart; however, notice that all dependencies flow away from it. Nobody need depend upon this class. Nobody except main needs to know that it exists. Thus, we’ve put the ugly bit behind a fence. It’s ugliness need not leak out and pollute the rest of the application.

I think the line 'notice that all dependencies flow away from it' is an important one here

于 2009-01-17T06:52:54.457 回答