子类专用属性的设计模式 [英] Design pattern for specialized properties in subclasses
问题描述
重复的 C#访问子类属性我们有一个对象模型,其中每个对象都有一个父项,而我想要访问父属性。
Duplicate of C# Accessing a subclass property - see additional solution approaches there.
与每个对象的具体类型。例如车轮应具有Car类型的母体属性。我的猜测是,有一个已经建立的设计模式来实现这一点(在.NET中)。然而,我没有找到它,所以我想出的设计看起来像这样
I have an object model where each object has a parent and I would like to access the parent property with the specific type for each object. So e.g. Wheel shall have a parent property of type Car. My guess is that there is an established design pattern for achieving this (in .NET). However, I have not found it so the design I came up with looks like this
public class BaseObject<T> where T : BaseObject<T>
{
private T mParent;
protected T Parent
{
get { return mParent; }
}
public BaseObject(T parent)
{
mParent = parent;
}
public void Save() ...
public void Delete() ...
public BaseObject<T> Clone() ...
}
public class Car : BaseObject<Car>
{
public Car(Car parent) : base(parent)
{
}
public bool Is4WD()
{
return true;
}
}
public class Wheel : BaseObject<Car>
{
public Wheel(Car parent) : base(parent)
{
}
public float RequiredTirePressure()
{
return Parent.Is4WD() ? 3.0f : 2.5f;
}
}
您是否看到这种方法有任何设计或性能缺陷?你可以推荐一个更好的设计吗?
Do you see any design or performance drawbacks with this approach? Can you recommend a better design?
推荐答案
答案是使用组合而不是继承。车轮不是车,所以不应该从 Car
延伸。相反,请在其构造函数中使轮
采取 Car
。
The answer is to use composition instead of inheritance. A wheel is not a car, so it should not extend from Car
. Instead, have the Wheel
take a Car
in its constructor.
例如:
public class Wheel {
private Car car;
public Wheel(Car car) {
this.car = car;
}
public float RequiredTirePressure() {
return car.Is4WD() ? 3.0f : 2.5f;
}
}
- 组合继承
- Composition over inheritance
这篇关于子类专用属性的设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!