开发者

Loading polymorphics objects - need pattern

I need some pretty approach to load polymorhic object

I have base class and several derived classes that base is not aware of. The only thing base class knows is Type enum wich defines which actual class it is.

class Order
{
 OrderType Type;

 bool Load(string filename)
 {
   // load Type
 }
}

class LimitOrder : Order
{

 // some data
 bool Load(string filename)
 {
   // load some data
 }
}

I need to w开发者_JAVA技巧rite a Load method for base class Order that would correctly create respective derived class. I am looking for a good pattern.


The simplest way is to use build-in binary serializer of .Net

 IFormatter formatter = new BinaryFormatter();
 Stream stream = new FileStream(filename, FileMode.Create, FileAccess.Write,     FileShare.None);
 formatter.Serialize(stream, obj);

And put this code in some sort of OrderFactory

class OrderFactory
{
   public static Order Load(string filename) {...}
   public static void Save(string filename, Order order) {...}
}


If you don't want to use the built-in serializers of .NET, you need some kind of factory method. You can place it in a separate factory object, or create a static function in your base class like that:

class Order
{
    public static Order CreateOrder(string filename)
    {
         Stream stream = new FileStream(filename);
         string typeinfo = stream.ReadLine();
         Type t=null;
         if(typeinfo=="LimitOrder")  // this can be improved by using "GetType"
            t=typeof(LimitOrder);
         else if(typeinfo==/* what ever your types are*/
            t= //...
         ConstructorInfo consInfo = t.GetConstructor(new Type[0]);
         Order o= (Order)consInfo.Invoke(new object[0]);
         o.Load(stream);
         stream.Close();
         return o;
    }
}

To get this working, every Order subclass must have a constructor with 0 parameters, and a virtual Load method with a stream parameter. And the first line in your file must be the typeinfo.


Since you have this requirement:

I have base class and several derived classes that base is not aware of. The only thing base class knows is Type enum wich defines which actual class it is.

In order to accomplish this, your derived classes will need to provide some form of registration with the base class. One approach could be to have a static Dictionary<MyTypeEnum,Func<Order>> defined in the base class, and allow subclasses to register themselves with the base class in order to add a specific creation function for their type to the base class dynamically. This way, when the file is parsed, the base class can just call the appropriate function to create the derived type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜