【发布时间】:2020-04-10 23:30:00
【问题描述】:
我有下一个场景: 有一个类负责管理应用程序的所有货币。所有货币都扩展了 Currency,因此它可以表现得像它。货币是抽象的,因此无法实例化。 在应用程序的某些部分中,我将软货币、硬货币或事件货币作为成本货币,例如,玩家按下某个菜单上的某个购买按钮。这个动作触发了一次购买,购买有货币作为参考,在这个例子中它可以是costSoftCurrency。 这个想法是,如果 PlayerCurrencies 收到货币,玩家货币会评估他的货币并返回相同类型的关联货币,然后您可以安全地减去成本。
我的问题是......如果没有这个可怕的 if,我怎么能得到相同的逻辑?我读到了double dispatch,但我不知道它是否可以在这里应用。
有谁知道这是否可以实现?
public class PlayerCurrencies
{
public SoftCurrency softCurrency = new SoftCurrency();
public HardCurrency hardCurrency = new HardCurrency();
public EventCurrency eventCurrency = new EventCurrency();
public Currency GetCurrencyFromType(Currency currency)
{
if (currency is SoftCurrency)
{
return this.softCurrency;
}
if (currency is HardCurrency)
{
return this.hardCurrency;
}
if (currency is EventCurrency)
{
return this.eventCurrency;
}
return null;
}
}
public abstract class Currency
{
public float Value
{
get;
set;
}
public void Add(Currency currency)
{
this.Value += currency.Value;
}
public void Substract(Currency currency)
{
this.Value -= currency.Value;
}
}
public class EventCurrency : Currency
{
}
public class HardCurrency : Currency
{
}
public class SoftCurrency : Currency
{
}
internal class Program
{
private static void Main(string[] args)
{
PlayerCurrencies playerCurrencies = new PlayerCurrencies();
Currency costSoftCurrency = new SoftCurrency();
Currency costHardCurrency = new HardCurrency();
playerCurrencies.GetCurrencyFromType(costSoftCurrency).Substract(costSoftCurrency); // there i get a SoftCurrency from Player Currencies
playerCurrencies.GetCurrencyFromType(costHardCurrency).Substract(costHardCurrency); // there i get a HardCurrency from Player Currencies
}
}
【问题讨论】:
-
听起来访问者设计模式可以提供帮助
-
您可以维护每种不同货币的集合。然后按类型检索货币,您可以使用
.OfType() -
Tbh 不同货币的整个不同类,然后搞乱类型似乎过于工程。功能方面,货币之间没有区别,所以对我来说,感觉应该只有一类。创建一个
enum以区分您的不同货币类型并将其传递给它的构造函数(使其成为只读字段)并在PlayerCurrencies类中保留一个Dictionary<CurrencyType, Currency>以直接访问不同的货币:return playerCurrencies[currency.Type]; -
有什么不对劲。您将
Currency作为参数传递,但您并不关心它的值。你只关心它的类型。如果您将其更改为GetCurrencyFromType(Type currencyType)并将currency.GetType()传递给它而不是currency,这将在功能上相同。这看起来应该是通用的,但我们不知道它是如何被调用的。最好从调用它的代码的角度来设计这样的东西。如果我们知道它需要做什么,我们可以帮助描述一些可以做的事情(也许)。 -
@ScottHannen 如果我按照您的建议将 Currency 的类型更改为 Type,然后永远不会触发
if(type is SoftCurrency),GetCurrencyFromType(Type type)总是返回 null。将其重构为 Type var 的正确方法是检查if(type == typeof(SoftCurrency)以保留相同的功能。
标签: c# architecture polymorphism