接口事件模式

时间:2014-07-29 20:03:32

标签: c# events design-patterns

public interface IConnector
{
       void Connect();
       event EventHandler<EventArgs> Received;

      // and more
}

public class ConnectorA: IConnector
{
     public event EventHandler<EventArgs> Received;

     public void Connect(){
     ...
     }
}

public class ConnectorB: IConnector
{
       public event EventHandler<EventArgs> Received;

       public void Connect(){
       ...
       }
}

现在假设我有一个这样的工厂:

public interface IConnectorFactory
{
    void Create(string type);
}

public class ConnectorFactory: IConnectorFactory
{
    public void Create(string type)
    {
        switch(type)
        {
            case "A":
                return new ConnectorA();
            case "B":
                return new ConnectorB();
        }
    }
}

我通过构造函数将此工厂注入到Manager类:

public class Manager
{
    IConnectorFactory _factory;
    IConnector _actualConnector;
    string _type;
    public string Type
    {
        get
        {
            return _type;
        }

        set
        {
            _type = value;
            if (_actualConnector != null)
            {
                _actualConnector.Disconnect();
                _actualConnector.Received -= ReceivedFunc;
            }

            _actualConnector = _factory.Create(Type);
            _actualConnector.Received += ReceivedFunc;
        }
    }

    public Manager(IConnectorFactory factory)
    {
        _factory = factory;
    }

    public void Connect()
    {
        _actualConnector.Connect();
    }

    public void DoSomethingElse()
    {
        _actualConnector.DoSomethingElse();
        _actualConnector.Received += ReceivedFunc;
    }

    public void ReceivedFunc()
    {
    }
}

Type是外部设置的属性(例如绑定到UI ComboBox)。问题是,每次更改我都必须取消订阅旧事件并订阅新事件。订阅界面事件是不是有一些模式?

1 个答案:

答案 0 :(得分:0)

_actualConnector分配值时:

_actualConnector = _factory.Create(Type);

您只是更改字段,旧对象仍然由Received处理ReceivedFunc事件。这与接口无关,这是对象和引用在.NET中的工作方式