我會對繼承模式保持公正,這會強制您在基本的,繼承的抽象類的上下文中執行操作。我認爲這是可取的原因是因爲它允許您輕鬆地封裝門的開啓和關閉,並且不會公開發生該情況的條件或在繼承場景之外的功能。
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