【发布时间】:2016-03-28 11:40:05
【问题描述】:
让我们考虑以下示例。我有这样的类的层次结构:
abstract class Base
{
public abstract void DoSomething();
}
class Foo : Base
{
public override void DoSomething()
{
Console.WriteLine("Foo. DoSomething...");
}
}
class Bar : Base
{
public override void DoSomething()
{
Console.WriteLine("Bar. DoSomething...");
if (ShouldDoSomethingElse)
{
DoSomethingElse();
}
}
public void DoSomethingElse()
{
Console.WriteLine("Bar. DoSomething else...");
}
public bool ShouldDoSomethingElse { get; set; }
}
我的客户是这样的:
class Program
{
static void Main(string[] args)
{
var foo = new Foo();
var bar = new Bar();
var items = new List<Base> {foo, bar};
HandleItems(items);
}
static void HandleItems(IEnumerable<Base> items)
{
foreach (var item in items)
{
if (item is Bar)
{
//Code smell! LSP violation.
var bar = item as Bar;
bar.ShouldDoSomethingElse = true;
}
item.DoSomething();
}
}
}
请注意,我们可以有多个客户端,其中一些可能需要 ShouldDoSomethingElse = 'true' 其他 'false'。
毫无疑问,在 HandleItems() 中以不同方式处理项目是设计不良和违反 Liskov 替换原则的标志。
您会建议什么方法或模式来消除这种代码异味?
如果有人问过类似的问题,我很抱歉。
【问题讨论】:
标签: c# oop solid-principles