Design pattern for specialized properties in subclasses

為{幸葍}努か 提交于 2019-12-25 06:47:01

问题


Duplicate of C# Accessing a subclass property - see additional solution approaches there.

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?


回答1:


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.

For example:

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


来源:https://stackoverflow.com/questions/10804578/design-pattern-for-specialized-properties-in-subclasses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!