簡體   English   中英

覆蓋嵌套的類函數或使用委托?**

[英]Overriding a nested class functions or use delegates?**

我有一個base class ,里面有嵌套類型。 外部(基礎)類型中有一個函數,稍后會被它的子項覆蓋。 事實上,這個函數屬於OO預期的inner type ,但我仍然需要它,被base class subtypes覆蓋。

我應該使用這個功能作為一個callbackinner type或只是移動它內部inner type ,讓我們的subtypes從那里覆蓋它?

編輯:添加了示例代碼

class A
{
    protected void func() { /* do something */ }
    class B { /**/ }
}

// OR

class A
{
    class B
    {
        protected void func() { /* do something */ }
    }
}

// Then

class C : A
{
    override func() { /**/ }
}

我的建議是為內部類型函數創建一個委托,該函數由基類的構造函數啟動:

internal class BaseClass
{
    public BaseClass(Action myAction)
    {
        this.innerType = new InnerType(myAction);
    }

    public BaseClass()
    {
        // When no function delegate is supplied, InnerType should default to
        // using its own implementation of the specific function
        this.innerType = new InnerType();
    }
}

如您所見,派生類型可以使用:base (overridenAction)調用基礎構造函數,在這里它們可以為最內層類型提供自己的函數實現。 當然,您沒有義務使用Action但您需要任何代理。

你正在描述的IMO看起來像戰略設計模式 考慮使用這種模式。 您的代碼將更易於維護,因為它包含可識別的模式。 你也可以看一下狀態設計模式 ,通常你必須在這兩者之間進行選擇,它們是緊密相連的。

在這種情況下:

class A
{
    class B
    {
        protected void func() { // do something }
    }
}

您不能從類A派生並覆蓋類B func()

根據您的描述,似乎A派生類應該能夠覆蓋內部類B中的某些功能(或功能),這表明您可能應該重新考慮您的設計。 要么提取B並且不要使它成為內部類,要么通過如下界面使您想要覆蓋顯式依賴的功能:

class A
{
    private B _MyB;
    public A(ISomeBehaviour behaviour)
    {
        _MyB = new B(behaviour);
    }
}

無論如何,如果你想堅持你的設計,那么我不建議使用委托方法,而是選擇覆蓋,因為如果在你的子課程中你需要的話,它會讓你更難添加裝飾。

這就是外部類可以作為內部服務類的策略的方式。

請注意,不建議使用TemplateMethod名稱(如TemplateMethodStrategy作為實際類名,請使用域中有意義的內容。 同樣適用於OuterInner

public class Consumer
{
    public void Foo()
    {
        IOuterFoo fooService = new Derived();
        fooService.OuterFoo();
    }
}

// ...

public interface IOuterFoo
{
    void OuterFoo();
}

abstract class Base : Base.IStrategy, IOuterFoo
{
    public void OuterFoo() { _service.Foo(); }

    private readonly InnerService _service;

    protected Base() { _service = new InnerService(this); }

    private interface IStrategy { void Foo(); }

    private class InnerService
    {
        private readonly IStrategy _strategy;
        public InnerService(IStrategy strategy) { _strategy = strategy; }
        public void Foo() { _strategy.Foo(); }
    }

    void IStrategy.Foo() { TemplateMethodFoo(); }

    protected abstract void TemplateMethodFoo();
}

class Derived : Base
{
    protected override void TemplateMethodFoo()
    {
        throw new NotImplementedException();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM