I have a class SuperItem which is abstract and implements some common methods and has some common properties . It also has some abstract methods that the sub items MUST implement on their own. A number of classes like AItem ,BItem ,CItem derive from SuperItem and implement some specific properties and the abstract methods from SuperItem.
I have a factory that returns a List but this list is created as:
class XYZ{
public Dictionary<string, SuperItemContainer> GetItemsByType(List<SomeClass> entries)
{
Dictionary<string, SuperItemContainer> itemsMap = new Dictionary<string,
SuperItemContainer>();
foreach (var entry in entries)
{
var item = ItemFactory.Create(entry);
List<SuperItem> itemsList = null;
if (itemsMap.ContainsKey(item.DataType))
{
itemsList = itemsMap[item.DataType].Items;
}
else
{
var container = new SuperItemContainer();
itemsList = container.Items;
itemsMap[item.DataType] = container;
}
itemsList.Add(item);
}
return itemsMap;
}
} So itemsMap will be where Container1 holds a list of SuperItems but they actually hold the subclass items A.
itemsMap will also have where Container2 holds a list of SuperItems but they actually hold the subclass items B and so on.
This is the ItemFactory.Create method:
public static DataTypeItem Create(SomeClass entry)
{
var dataType = entry.Model;
if (dataType == "A")
return new AItem(entry);
else if (dataType == "B")
return new BItem(entry, false);
else
return new BItem(entry, false);;
}
This is the superItem container that holds a list of SuperItems.
public class SuperItemContainer
{
public List<SuperItem> Items { get; set; }
public SuperItemContainer()
{
Items = new List<SuperItem>();
}
public string JSONSerializer(){
// TODO serialize the Items list based on the type
//i.e if A then serialize by taking specific properties in A ,
//if B then serialize with superclass properties
//if C then serialize with C properties
//if D then return empty string //etc
}
}
On this Container I need to implement a specific json serializer based on type.
This will be invoked from class XYZ above so that for the itemsMap , I can get a JSON for each entry in the map.
I know the sepcifics of serialization but am not sure how to design or redesign this such that serialzier can behave separately as per the subtype of the elements in the Items list.
An option would be to store the dataType string in the container instance but this makes my code messy as I dont have the datatype property at the XYZ class level , only have it at the factory class level.
Aucun commentaire:
Enregistrer un commentaire