简体   繁体   English

设计问题:需要一些关于如何构建我的类继承以避免代码重复的提示

[英]Design issue: Need some tips on how to structure my class inheritance to avoid duplication of code

Let's assume I have some logic implemented in a class called "Geometry".假设我在名为“Geometry”的类中实现了一些逻辑。 My class "Line" inherits from Geometry and implements some functionality to draw a line in 2d and my other class "Circle" inherits again from Geometry and draws circles in 2d.我的类“Line”继承自 Geometry 并实现了一些功能以在 2d 中绘制一条线,而我的另一个类“Circle”再次从 Geometry 继承并在 2d 中绘制圆。 Now I'm creating another class Geometry3d : Geometry which adds features on top of Geometry in effect forcing all inherited classes to operate in 3d space.现在我正在创建另一个类 Geometry3d : Geometry 它在 Geometry 之上添加功能实际上迫使所有继承的类在 3d 空间中运行。 And here I'm running into this problem - I'd like to reuse all my code from Line and Circle classes, but have them inherit from the Geometry3d class as well, turning them into Line3d and Circle3d classes.在这里我遇到了这个问题 - 我想重用 Line 和 Circle 类中的所有代码,但让它们也继承自 Geometry3d 类,将它们转换为 Line3d 和 Circle3d 类。 Is this achievable without duplicating code?这是否可以在不重复代码的情况下实现?

For example how do I accomplish this:例如我如何做到这一点:

var myCircle2d = new Circle(); // this would be Geometry : Circle
var myCircle3d = new Circle3d(); // this would be Geometry : Geometry3d: Circle: Circle3d

Note that the code in the Circle class is the same and the Circle3d class would be an empty container请注意,Circle 类中的代码是相同的,Circle3d 类将是一个空容器

Is there a design pattern to make it possible to inject a parent like that?是否有一种设计模式可以像这样注入父级?

You can't have inheritance from multiple base classes in C#.在 C# 中不能从多个基类继承。 You can usually solve this with composition.您通常可以通过组合解决此问题。 You could make Geometry3D contain the Geometry as a member variable as follows:您可以使 Geometry3D 包含 Geometry 作为成员变量,如下所示:

class GenericGeometry3D<T> : Geometry3D where T : Geometry{
    T InnerGeometry;
    public GenericGeometry3D(T innerGeometry){
        InnerGeometry = innerGeometry;
    }

    //implement functionality of Geometry by redirecting to the inner geometry
    //you can auto generate these methods in VS by selecting 'Implement through'
    public void MethodInGeometry(){
       InnerGeometry.MethodInGeometry();
    }
    //...

    //extra functionality provided by Geometry3D
    //...
}

You will then automatically have GenericGeometry3D<Circle> and GenericGeometry3D<Line> classes.然后您将自动拥有GenericGeometry3D<Circle>GenericGeometry3D<Line>类。 I'm not sure if this pattern has a name.我不确定这个模式是否有名字。 It is a bit similar to the decorator pattern.它有点类似于装饰者模式。

You can then create Circle3D as follows:然后,您可以按如下方式创建 Circle3D:

class Circle3D : GenericGeometry3D<Circle>{
  public Circle3D(...) : base (new Circle(...)) { }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM