我对编程相当陌生,我很难理解如何有效地应用以下链接(ATM 链接)中显示的原则:
http://www.objectmentor.com/resources/articles/isp.pdf
基本上,它从不抱怨 ISP(接口隔离原则)的设计开始,然后继续将行为重构为不同的接口。
我的问题是:我们不使用接口来表达不那么(或不)相关的抽象之间的共同行为吗?
将方法封装在接口中的意义何在,即使没有一个方法与将要实现它们的类共享?在哪种情况下这可能被认为是有用的?
如果我们继续该示例的行,则给出以下代码:
public interface ITransaction
{
void Execute();
}
public interface IDepositUi
{
void RequestDepositAmount();
}
public class DepositTransaction : ITransaction
{
private IDepositUi depositUI;
public DepositTransaction(IDepositUi ui)
{
depositUI = ui;
}
public virtual void Execute()
{
/*code*/
depositUI.RequestDepositAmount();
/*code*/
}
}
public interface WithdrawalUI
{
void RequestWithdrawalAmount();
}
public class WithdrawalTransaction : ITransaction
{
private WithdrawalUI withdrawalUI;
public WithdrawalTransaction(WithdrawalUI ui)
{
withdrawalUI = ui;
}
public virtual void Execute()
{
/*code*/
withdrawalUI.RequestWithdrawalAmount(); /*code*/
}
}
public interface TransferUI
{
void RequestTransferAmount();
}
public class TransferTransaction : ITransaction
{
private TransferUI transferUI;
public TransferTransaction(TransferUI ui)
{
transferUI = ui;
}
public virtual void Execute()
{
/*code*/
transferUI.RequestTransferAmount();
/*code*/
}
}
public interface UI : IDepositUi, WithdrawalUI, TransferUI
{
}
据我了解,为了使用以前的设计,我们应该有类似的东西:
UI impui = new IMPLEMENTATIONUI(); // Some UI implementation
DepositTransaction dt = new DepositTransaction(Gui);
dt.Execute();
现在,我们不需要 IMPLEMENTATIONUI 实现每一个方法吗?如果是这样,它不会破坏 SRP 吗?