谁能告诉我哪种设计最适合这种情况?
我有名为 BasicAccount
、SavingAccount
和 CurrentAccount
的类。
SavingAccount
和 CurrentAccount
应该具有 BasicAccount
的所有功能。稍后我们可能会引入一个名为 AdvanceAccount
的新帐户,它应该具有 CurrentAccount
和 SavingAccount
的所有功能。结构应该怎么设计?
我的回答:
让
BasicAccount
保持抽象,SavingAccount
也是抽象的,并实现BasicAccount
创建一个接口(interface)
ICurrentAccount
和 currentaccount 实现BasicAccount
和ICurrentAccount
,如果我们有
AdvanceAccount
,则使用SavingAccount
和ICurrentAccount
实现它。
有没有更好的办法?这是在面试中被问到的,我想面试官对我的回答不满意。
最佳答案
我会使用这样的东西:
abstract class BasicAccount {}
interface ISavingAccount {}
interface ICurrentAccount {}
class SavingAccount : BasicAccount, ISavingAccount {}
class CurrentAccount : BasicAccount, ICurrentAccount {}
class AdvanceAccount : BasicAccount, ISavingAccount, ICurrentAccount {}
如果SavingAccount
和CurrentAccount
有很多功能,可以在AdvanceAccount
实现中使用聚合:
class AdvanceAccount : BasicAccount, ISavingAccount, ICurrentAccount
{
private readonly SavingAccount savingAccount;
private readonly CurrentAccount currentAccount;
public AdvanceAccount()
{
savingAccount = new SavingAccount(...);
currentAccount = new CurrentAccount(...);
}
// redirect ISavingAccount and ICurrentAccount implemetation
// to savingAccount and currentAccount respectively
}
UPD。
请注意,在 AdvanceAccount
中直接实例化 SavingAccount
和 CurrentAccount
只是一个示例。 IRL 你可能会使用 IoC 容器。
关于c# - 哪种设计最适合这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33031344/