简体   繁体   中英

Design pattern for translating data

I am working on a C# project and I need to manage a local cache of data and present it on a GUI.

For example I have:

    public class DataFromOtherLibrary

Now I want make a class to help translate the information I need out of it

    public class MyDataModel
    {
            private DataFromOtherLibrary cache;
            public MyDataModel ( DataFromOtherLibrary Source)
            {
                    cache = Source;
            }
            public long Field1 { get { return cache.SomeField; } }
            public long Field2 { get { return cache.OtherFiled; } }
     }

Now the issue I have is I need to create a MyDataModel for every DataFromOtherLibrary it would be nice to have a single translator class. I'm not sure how to do it and still implement properties (which I need to data-bind to).

Thanks Matt

You should use a Provider with all your DataModels in it Like:

public class MyDataModelProvider
{
    public List<MyDataModel> DataModelList { get; set; }

    MyDataModelProvider()
    {
        loadDataModelList();
    }

    private void LoadDataModel()
    {
        foreach (Cachobject c in Cache)
        {
            this.DataModelList.Add(new MyDataModel(c.valueA,c.valueB));
        }
    }
}

and for this Provider you also need a Factory Like:

[Singleton(true)]
public class DataModelListProviderFactory
{
    private static DataModelListProvider dataListProvider;
    public DataModelListProvider getInstance()
    {
        if (dataListProvider == null)
        {
            dataListProvider = new DataModelListProvider();
           return dataListProvider;
        }
        else
            return dataListProvider;
    }
}

Because now you have a single Spot with all your DataModels and you only must recieve them once. You can also easily search the List for a specific Model if you have a case or you show all the Data in a View.

You can read here more about Factory Patterns.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM