lundi 14 août 2017

Implement extensibility on callback?

Currently, I am working on an API, and developers can subscribe to it to know the updates.

So right now I am implementing an interface IResult , so that I can send different parameters in the callback result. The problem right now is if in the future, I want to add a new callback, I have to add an argument in the method, and developers also need to change their method call. Is there a good solution for this?

public interface IResult
{
    int i { get; set; }
}

public class ConcreteResult : IResult
{
    public int i
    {
        get;set;
    }
}


public class MyAPI
{
    public delegate void MyAPIDelegate(IResult result);

    public void StartService(MyAPIDelegate callback, MyAPIDelegate callback2)
    {
        //step 1
        int i = 0;
        ConcreteResult result1 = new ConcreteResult();
        result1.i = i;
        callback(result1);
        //step 2
        i += 1;
        ConcreteResult result2 = new ConcreteResult();
        result2.i = i;
        callback2(result2);
        //potentially added in the future
        //i += 1;
        //callback3();
    }

    public void main()
    {
        //developers use my API
        StartService(developerCallback, developerCallback2);
    }
    private void developerCallback(IResult result)
    {
        Console.WriteLine(result.i);
    }
    private void developerCallback2(IResult result)
    {
        Console.WriteLine(result.i);
    }
}

Aucun commentaire:

Enregistrer un commentaire