Is this on a right creational pattern way?

110 views Asked by At

I'm new to design patterns, and wondering what the particular kind of design pattern is (if there's any) inside the code snippet listed below.

Basically there's a base class, which knows how to build a BaseProperty object:

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;
        }
    }
}

, and here goes a subclass implementing its own property building details

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;
    }
}

In this code I implemented the factory pattern, as can be seen that the subclass implements its own property creation method. The purpose is to collect properties of all the created objects for persistent storage.

What confused me is that, after being created the BaseProperty object is then "manufactured" in an incremental way, starting from base.BuildProperty(prop) which builds fundamental part, and then the object is down cast to a NumberProperty for building its subclass-specific part.

Am I doing right? There's a down casting operation... should it be avoided? If so, how to do that?

Thanks!

0

There are 0 answers