我们使用域对象封装业务逻辑。有时,由于新的系统要求,我们需要更改实体的行为。一种常见的方法是通过添加检查功能标志的IF语句来修改方法或属性:
public class Entity : IEntity
{
public void SomeMethod()
{
if (Feature.NewRequirement())
{
DoTheNewStuff();
}
else
{
DoTheOldStuff();
}
}
}
功能标志确定何时应启用新行为,并允许我们在必要时将其关闭。通常,该功能在生产中运行了几个星期或几个月之后,我们删除了标志并仅保留新实施。 使用这种方法的问题
FEATURE标志作为静态依赖性 - 功能类是静态的,并且 取决于持有功能标志配置的缓存。这使得 单位测试困难,因为在测试中共享状态可能导致 脆性并防止并行执行。
根据功能标志封装不同的行为。
public interface ISomeMethodStrategy
{
void Execute();
}
public class OldSomeMethodStrategy : ISomeMethodStrategy
{
public void Execute() => DoTheOldStuff();
}
public class NewSomeMethodStrategy : ISomeMethodStrategy
{
public void Execute() => DoTheNewStuff();
}
策略的新域实体
public class Entity : IEntity
{
private readonly ISomeMethodStrategy _strategy;
public Entity(ISomeMethodStrategy strategy)
{
_strategy = strategy;
}
public void SomeMethod() => _strategy.Execute();
}
然后,在创建实体之前,请确定要使用的策略:
var strategy = featureService.IsNewRequirementEnabled()
? new NewSomeMethodStrategy()
: new OldSomeMethodStrategy();
var entity = new Entity(strategy);