dimanche 30 août 2020

How to apply Factory Pattern, Interface does not have method (belongs to implemented class)

I am applying Factory Pattern. There is an interface and two classes inherit from the interface.

Also, I created a class whose role is create an factory object. If I created factory object, there is an error. "No overload method". Because this method not in the interface.

How to implement factory method with factory object, for extra method.

        [Test]
    public void XML_Deserialize_ToObject_FromURL_WithRootAttirbuteName()
    {
        var xmlSerializerTCMB = GenericSerializer<Tarih_Date>.CreateSerializerObject(DataFormatType.XML);

        var kur = xmlSerializerTCMB.DeserializeFromLink("https://www.tcmb.gov.tr/kurlar/today.xml", "Tarih_Date");

        Assert.IsTrue(kur.Currency.Length > 0);
    }

Pieces of code listed below

Interface

public interface IGenericSerializer<T>
{
    void SerializeToFile(T objectData, string fileName);
    string SerializeToString(T objectData);
    T DeserializeFromFile(string fileName);
    T DeserializeFromString(string mediaTypeString);
    T DeserializeFromLink(string link);
}

XmlGenericSerializer, this method have extra method(DeserializeFromLink) which is not belongs to the interface.

public class XmlGenericSerializer<T> : IGenericSerializer<T>
{
    public T DeserializeFromFile(string fileName)
    {

    }

    public T DeserializeFromLink(string link)
    {

    }

    public T DeserializeFromString(string xmlString)
    {

    }

    public void SerializeToFile(T objectData, string fileName)
    {

    }

    public string SerializeToString(T objectData)
    {

    }

    public T DeserializeFromLink(string link, string xmlRootAttributeName)
    {

    }
}

JsonGenericSerializer

 public class JsonGenericSerializer<T> : IGenericSerializer<T>
{
    public T DeserializeFromFile(string fileName)
    {

    }

    public T DeserializeFromLink(string link)
    {
        
    }

    public T DeserializeFromString(string jsonString)
    {
       
    }

    public void SerializeToFile(T objectData, string fileName)
    {            
        
    }

    public string SerializeToString(T objectData)
    {
         
    }
}

Factory class

        public static class GenericSerializer<T>
{ 

    public static IGenericSerializer<T> CreateSerializerObject(DataFormatType dataFormat)
    {
        IGenericSerializer<T> serializer = null;
        switch (dataFormat)
        {
            case DataFormatType.XML:
                serializer = new XmlGenericSerializer<T>();
                break;
            case DataFormatType.JSON:
                serializer = new JsonGenericSerializer<T>();
                break;
            default:
                break;
        }

        return serializer;
    }
}

Aucun commentaire:

Enregistrer un commentaire