考虑以下abstract
基类和子类。
public abstract class SerializableObject<T> : IByteSerializable<T>
{
public abstract IByteSerializableFactory<T> GetFactory();
}
public abstract class SerializableObjectFactory<T> : IByteSerializableFactory<T>
{
public abstract byte[] GetBytes(T obj);
public abstract T GetObject(byte[] bytes);
}
public class UID : SerializableObject<UID>
{
public string UniqueID { get; private set; }
internal UID(string uid)
{
UniqueID = uid;
}
public override IByteSerializableFactory<UID> GetFactory()
{
return new UIDFactory();
}
}
public class UIDFactory : SerializableObjectFactory<UID>
{
public static Encoding CharacterEncoding = Encoding.ASCII;
public UID CreateObject(string uid)
{
return new UID(uid);
}
public override byte[] GetBytes(UID obj)
{
return CharacterEncoding.GetBytes(obj.UniqueID);
}
public override UID GetObject(byte[] bytes)
{
try
{
return CreateObject(CharacterEncoding.GetString(bytes));
}
catch (Exception ex)
{
//...
}
}
}
在这样的Factory类中使用GetObject(byte[] bytes)
方法的唯一方法就是这样调用它吗?
static void Main(string[] args)
{
byte[] bytes = ...
UID uid = new UIDFactory().GetObject(bytes);
}
每次我需要将UIDFactory
数据反序列化为byte[]
对象时,实例化UID
是不是效率低下?
这是另一种情况,我应该放弃担心并让CLR处理它吗?
答案 0 :(得分:1)
您的UIDFactory
对象使用默认构造函数,因此涉及的工作量很少。根据您实例化它的频率,这似乎不是一个大问题。
也许在整个main
或使用单身人士保持实例活着会有所帮助。