1

我是设计模式的新手,想知道下面列出的代码片段中特定类型的设计模式是什么(如果有的话)。

基本上有一个基类,它知道如何构建一个 BaseProperty 对象:

public abstract class Base
{
    private string m_name;

    public class BaseProperty
    {
        public string Name;
    }

    protected virtual BaseProperty NewProperty()
    {
        return new BaseProperty();
    }

    protected virtual void BuildProperty(ref BaseProperty prop)
    {
        prop.Name = m_name;
    }

    public BaseProperty Property
    {
        get
        {
            BaseProperty prop = NewProperty();
            BuildProperty(ref prop);

            return prop;
        }
    }
}

, 这里有一个子类实现它自己的属性构建细节

public class Number : Base
{
    private double m_number;
    public class NumberProperty : BaseProperty
    {
        public double Number;
    }

    protected override BaseProperty NewProperty()
    {
        return new NumberProperty();
    }

    protected override virtual void BuildProperty(ref BaseProperty prop)
    {
        // build the common part
        base.BuildProperty(ref prop);

        // build my specific part
        NumberProperty numberProp = prop as NumberProperty;
        numberProp.Number = m_number;
    }
}

在这段代码中,我实现了工厂模式,可以看出子类实现了自己的属性创建方法。目的是收集所有创建对象的属性以进行持久存储。

让我感到困惑的是,在创建 BaseProperty 对象之后,然后以增量方式“制造”,从base.BuildProperty(prop)构建基本部分开始,然后将对象向下转换NumberProperty为构建其子类特定部分的对象。

我做得对吗?有一个向下铸造操作......应该避免吗?如果是这样,该怎么做?

谢谢!

4

0 回答 0