gpt4 book ai didi

c# - 访问者模式和封装

转载 作者:太空狗 更新时间:2023-10-29 18:19:07 25 4
gpt4 key购买 nike

访问者设计模式是一种将算法与其运行的对象结构分开的方法。这是它的官方定义。我试图弄清楚这如何不破坏封装。例如,如果我有不同类型的类用于不同类型的银行账户 [储蓄/固定/当前] 实现抽象类账户,我应该将计算利息方法作为抽象方法放在抽象账户类中还是发送账户键入访问者实现并在那里计算它?

方法 1:访客实现是否应负责计算不同帐户类型的利息?

public interface IInterestVisitor
{
void GetInterest(Savings AccountType);
void GetInterest(Fixed AccountType);
void GetInterest(Current AccountType);
}

方法 2:还是应该由 Account 类的实现者来做?

public abstract class Account
{
public abstract void AcceptCalculateInterestVisitor(IInterestVisitor iv);
public abstract int CalculateInterestAmount();
}

如果我使用方法 1,也就是上面实现 IInterestVisitor 的访问者实现,那么计算利息的工作将委托(delegate)给访问者类。使用这种方法,如果我添加另一种帐户类型,那么每次出现新帐户时我都需要修改访问者实现。

但是,如果我在方法 2 中将利息计算位留给抽象帐户类实现,那么在我看来[如果我在这里错了请纠正我] 我没有破坏封装。此外,需要修改的代码更少,因为我所做的只是添加一个新类并让访问者实现如下所示的接口(interface)

public interface IInterestVisitor
{
void GetInterest(Account AccountType);
}


public class InterestVisitor : IInterestVisitor
{
public void GetInterest(Account AccountType)
{
int i = AccountType.CalculateInterestAmount();
Console.WriteLine(i);
}
}

如您所见,使用方法 2 的兴趣访问者类无需修改。方法 1 是否破坏了封装?方法二还能叫访客模式吗?

感谢阅读...

最佳答案

Visitor lets you define a new operation without changing the classes of the elements on which it operates.

在提供的代码中,我看不到您需要更改对象以满足您的需求,Visitor基本上,是通过使用提供的 Properties 来更改对象状态/Methods/Fields对象本身。

所以,根据我的说法,您的代码可以符合访客模式,如果这确实是个问题,也因为模式是指南不是严格的规则。

我个人会选择第二种方式,因为它更加清晰且面向 OOP。

问候。

关于c# - 访问者模式和封装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7059502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com