【问题标题】:Design pattern to inherit derived members from non-modifiable base classes?从不可修改的基类继承派生成员的设计模式?
【发布时间】:2021-09-15 05:44:45
【问题描述】:

我有以下鸡/蛋继承问题:

这里是我可以派生的基类,但它们位于框架上,因此我无法修改它们:

class Editor
{

}

class ScriptedImporterEditor : Editor
{
}

这里是我项目中的类:

一个带预览的编辑器,按预期工作,CylinderTorusDrawPreview

class EditorWithPreview : Editor
{
    public void DrawPreview(){}
}
   
class Cylinder : EditorWithPreview
{
    // DrawPreview is available
}

class Torus : EditorWithPreview
{
    // DrawPreview is available
}

但现在我需要一个可以预览的脚本导入器编辑器:

class ScriptedImporterEditorWithPreview : ScriptedImporterEditor
{
    // cannot inherit EditorWithPreview as it's not a ScriptedImporterEditor
}

class Cube : ScriptedImporterEditorWithPreview 
{
    // unable to use DrawPreview
}

class Sphere : ScriptedImporterEditorWithPreview 
{
    // unable to use DrawPreview
}

基本上,

  • EditorScriptedImporterEditor 我都无法更改,因为我不拥有它们
  • 因此我无法将EditorWithPreview 的逻辑导入ScriptedImporterEditor
  • CubeSphere不能继承和使用DrawPreview

【问题讨论】:

    标签: c# inheritance design-patterns


    【解决方案1】:

    以下可能会有所帮助。

    class ScriptedImporterEditorWithPreview : ScriptedImporterEditor
    {
        private EditorWithPreview editorWithPreview = null;
        public ScriptedImporterEditorWithPreview(EditorWithPreview editorWithPreview)
        {
             this.editorWithPreview = editorWithPreview;
        }
        public virtual void DrawPreview()  // based on need it is virtual or non-virtual
        {
             this.editorWithPreview.DrawPreview();
        }
    }
    
    class Cube : ScriptedImporterEditorWithPreview 
    {
        
    }
    
    class Sphere : ScriptedImporterEditorWithPreview 
    {
        
    }
    

    【讨论】:

    • 由于 XYZ 的原因,最终结果大不相同,但确实让我找到了解决方案。 ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    相关资源
    最近更新 更多