开发者

Pattern for notifying an application that a collection has changed?

开发者 https://www.devze.com 2022-12-20 18:28 出处:网络
Say I have a basic interface like the following: public interface IObjectProvider { IEnumerable<IObject> GetObjects();

Say I have a basic interface like the following:

public interface IObjectProvider
{
    IEnumerable<IObject> GetObjects();
}

The object source is some backing store that might be updated, and the implementation of this interface takes care of using that backing store. Now I'd like consumers of this interface to be able to take actions whenever the collection of objects provided by this interface changes. How would you restructure this interface to provide this ability? I'd like the result to be usable for many "provider" interfaces in the application for good design consistency.

Example: The following provides this feature in a concise and understandable way, but adds significant coupling (including 开发者_如何学编程references to the WPF assemblies in pre-.NET 4.0 code). Should I just use this since we know that once code goes to .NET 4.0 it will automatically be "lighter"?

public interface IObjectProvider
{
    ReadOnlyObservableCollection<IObject> Objects
    {
        get;
    }
}

Edit 1:

Based on Reed's answer, I'm leaning towards leaving the IObjectProvider interface unchanged for the following reasons:

  • This is a new application, so the design can be documented early and followed with consistency throughout.
  • Declare that for all providers, if the provider supports notifications that the provided collection changed, then the value returned by GetObjects() will necessarily implement INotifyCollectionChanged.

There are two other cases raised by this that I still need to account for in my design:

  • The provided collection never changes.
  • The provided collection might change, but the client would need to poll if it wanted the updates. Could I just make the claim that this case won't exist in the application (and is that a good idea)?


You could always use the interfaces for this, such as INotifyPropertyChanged and INotifyCollectionChanged.

This would allow you to use a custom collection, and standard interfaces, without taking references to WPF.

0

精彩评论

暂无评论...
验证码 换一张
取 消