jeudi 28 juillet 2016

Design pattern for child class that contains child property

I'm wondering if there is a design pattern that would solve this problem. I have a structure that looks like this:

    public abstract class DBAccess
    {
         protected MetaData metaData;
    }

    public class OldDBAccess: DBAccess
    {
         //this class will set metatData = new OldDBMetaData(); in the constructor
    }

    public class NewDBAccess: DBAccess
    {
         //this class will set metaData = new NewMetaData(); in the constructor
    }

    public abstract class MetaData
    {
        //some variables and methods that belong to all MetaData objects
    }

    public class OldDBMetaData : MetaData
    {
        string oldName;
        //some variables and methods that belong to only OldDBMetaData objects
    }

    public class NewDBMetaData : MetaData
    {
        //some variables and methods that belong to only NewDBMetaData
    }

I want to be able to call a method in OldDBAcess that sets properties that belong to OldDBMetaData. Since metaData is a MetaData object and not an OldDBMetaData object, I've had to do this so far:

    //method in OldDBAccess
    public void SetOldName(string name)
    {
       if(metaData is OldMetaData)
       {
           OldMetaData metaData = (OldMetaData)AccountMetaData;
            if (metaData == null)
                // metaData isn't of type OldMetaData
            else
                metaData.oldName = name;
        }
     }

This works just fine, I just don't want to have to check that metaData is of type OldMetaData every time I call a method. I know that it's of this type because I set it to this type in the constructor. I want to use the metaData property in either of the derived classes or the base class, so I can't just create properties in each of the DBAccess classes. Is there a design pattern or some easy way to do this with this kind of structure?

Aucun commentaire:

Enregistrer un commentaire