我有一个设计问题,需求是这样的:
我正在考虑两种设计方案:
你觉得哪种更好,原因是什么。
发布于 2017-10-18 04:21:23
尽管第2种方法遵循OOAD的开放/封闭原则(),即您将添加新的接口实现,每次添加新类型时都不会修改现有代码,这是非常安全的方法,因为它不需要对旧代码/方法进行测试。因此,您的代码将对扩展开放,但因修改而关闭。但是,如果您要经常添加新类型,那么方法2是有意义的。
在本例中,我建议使用方法1,因为业务需求非常简单,即根据参数类型生成字符串。因此,在我看来,使用接口将是过度工程(如果类型不会经常添加)。
发布于 2017-10-18 06:03:10
为这个问题声明使用一些设计模式将是很好的,以使您的代码更加健壮和可重用。我将建议您的战略设计模式。使用接口的是基于抽象的模式。
基本例子:
public interface IMyStrategy
{
string Generate(string someValue);
}
public class StragegyA : IMyStrategy
{
public string Generate(string somevalue)
{
return /Implementation/;
}
}
public class StragegyB : IMyStrategy
{
public string Generate(string somevalue)
{
return /Implementation/;
}
}
public class MyStrategyContext
{
private readonly IMyStrategy _ImyStrategy;
public MyStrategyContextIMyStrategy(IMyStrategy myStragegy)
{
_ImyStrategy = myStragegy
}
public string GenerateResult(string someValue)
{
return _ImyStrategy .Generate(someValue);
}
}
[Test]
public void GenerateValue()
{
var abc = new MyStrategyContext(new StragegyA());
abc.GenerateResult("hey print");
}https://stackoverflow.com/questions/46798978
复制相似问题