我会对继承模式保持公正,这会强制您在基本的,继承的抽象类的上下文中执行操作。我认为这是可取的原因是因为它允许您轻松地封装门的开启和关闭,并且不会公开发生该情况的条件或在继承场景之外的功能。
public void Main()
{
var x = new InheritedAction();
}
public abstract class BaseGateAction
{
public void PerformBaseAction(Action actionToPerformWhileGateIsOpen)
{
Open();
actionToPerformWhileGateIsOpen();
Close();
}
private void Open()
{
Console.WriteLine("Gate has been opened");
}
private void Close()
{
Console.WriteLine("Gate has been closed");
}
}
public class InheritedAction : BaseGateAction
{
public InheritedAction()
{
PerformBaseAction(() =>
Console.WriteLine("Attack the dragon while the gate is open"));
PerformBaseAction(() =>
{
Console.WriteLine("Attack the dragon while the gate is open");
Console.WriteLine("The dragon is victorious and you have been devoured");
});
}
}
此代码示例输出用于既PerformBaseAction方法以下分别称之为:
Gate has been opened
Attack the dragon while the gate is open
Gate has been closed
Gate has been opened
Attack the dragon while the gate is open
The dragon is victorious and you have been devoured
Gate has been closed
这将允许不仅更好的代码重用,但远多个封装的逻辑。您总是可以添加额外的暴露方法,这些方法会采用会影响您是否可以打开大门的先决条件或后置条件。
public abstract class BaseGateAction
{
....
public void PerformBaseActionWithPrecondition(Func<bool> precondition, Action actionToPerformWhileGateIsOpen)
{
if (precondition())
{
PerformBaseAction(actionToPerformWhileGateIsOpen);
}
else
{
Console.WriteLine("The gate could not be opened!");
}
}
...
}
这可以被称为如下:
PerformBaseActionWithPrecondition<bool>(
() => true == false,
() => Console.WriteLine("Attack!")
);
,并会输出:
The gate could not be opened!
工作的代码是题外话了StackOverflow上。你可能想看看[代码评论](http://codereview.stackexchange.com/)。 – 2015-02-10 00:56:35
这一切都取决于注释掉的代码是什么。如果有一种方法可以重用它,那么一定要保持单一的方法。 @ Pierre-LucPineault建议在Code Review上发布完整的代码。 – krillgar 2015-02-10 00:58:16
但是,请注意Code Review不允许存根代码。你将不得不发布整个方法。 – Hosch250 2015-02-10 00:59:04