Reputation: 25
Let's assume I have some logic implemented in a class called "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. 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. 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. 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
Is there a design pattern to make it possible to inject a parent like that?
Upvotes: 1
Views: 102
Reputation: 1729
You can't have inheritance from multiple base classes in C#. You can usually solve this with composition. You could make Geometry3D contain the Geometry as a member variable as follows:
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. 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:
class Circle3D : GenericGeometry3D<Circle>{
public Circle3D(...) : base (new Circle(...)) { }
}
Upvotes: 1