另一种选择是使用 Pub/Sub 模式。使用此模式,您可以让每个 User 实例订阅发布者可以发送的特定发布消息。
这种用法的一个例子是这样的:
User1 类
public class User1 : IDispose
{
private ISubscription subscription;
public User1(NotificationManager notificationManager)
{
this.subscription = notificationManager.Subscribe<WakeUpNotification>(
(notification, subscription) => this.WakeMeUp());
}
public void WakeMeUp()
{
Console.WriteLine("Ringing User1's Alarm");
}
public void Dispose()
{
this.subscription.Unsubscribe();
}
}
User2 类
public class User2 : IDispose
{
private ISubscription subscription;
public User2(NotificationManager notificationManager)
{
this.subscription = notificationManager.Subscribe<StartMyTvNotification>(
(notification, subscription) => this.StartMyTv());
}
public void StartMyTv()
{
Console.WriteLine("Ringing User1's Alarm");
}
public void Dispose()
{
this.subscription.Unsubscribe();
}
}
某处的应用类
var notificationManager = new NotificationManager();
var user1 = new User1(notificationManager);
var user2 = new User2(notificationManager);
notificationManager.Publish(new WakeUpNotification(true));
notificationManager.Publish(new TurnOnMyTvNotification(DateTime.Now));
user1.Dispose();
这可以与计时器结合使用,允许以不同的时间间隔发布消息。您可以使用 Timer 在与发布 TurnOnMyTvNotification 时不同的时间发布 WakeUpNotification。
发布/订阅实现
以下是发布/订阅设置的实现。代码有很好的文档记录。
INotificationCenter
/// <summary>
/// Provides a contract for Mediators to use when handling notifications between objects.
/// </summary>
public interface INotificationCenter
{
/// <summary>
/// Sets up a new handler and returns it for subscription set up.
/// </summary>
/// <typeparam name="TMessageType">An IMessage implementation that the given handler will be provided when messages are dispatched</typeparam>
/// <param name="handler">The handler used to process incoming messages.</param>
/// <returns>Returns an ISubscription that can be used to unsubscribe.</returns>
ISubscription Subscribe<TMessageType>(Action<TMessageType, ISubscription> callback, Func<TMessageType, bool> condition = null) where TMessageType : class, IMessage;
/// <summary>
/// Publishes the specified message.
/// </summary>
/// <typeparam name="TMessageType"></typeparam>
/// <param name="message">The message.</param>
void Publish<TMessageType>(TMessageType message) where TMessageType : class, IMessage;
}
通知管理器
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
/// <summary>
/// The mediator for all messaging
/// </summary>
public class NotificationManager : INotificationCenter
{
/// <summary>
/// Collection of subscribed listeners
/// </summary>
private ConcurrentDictionary<Type, List<ISubscription>> listeners =
new ConcurrentDictionary<Type, List<ISubscription>>();
/// <summary>
/// Subscribe publications for the message type specified.
/// </summary>
/// <typeparam name="TMessageType">A concrete implementation of IMessage</typeparam>
/// <returns></returns>
public ISubscription Subscribe<TMessageType>(Action<TMessageType, ISubscription> callback, Func<TMessageType, bool> condition = null) where TMessageType : class, IMessage
{
ExceptionFactory.ThrowIf(
callback == null,
() => new ArgumentNullException(nameof(callback), "Callback must not be null when subscribing"));
Type messageType = typeof(TMessageType);
// Create our key if it doesn't exist along with an empty collection as the value.
if (!listeners.ContainsKey(messageType))
{
listeners.TryAdd(messageType, new List<ISubscription>());
}
// Add our notification to our listener collection so we can publish to it later, then return it.
// TODO: Move instancing the Notification in to a Factory.
var handler = new Notification<TMessageType>();
handler.Register(callback, condition);
handler.Unsubscribing += this.Unsubscribe;
List<ISubscription> subscribers = listeners[messageType];
lock (subscribers)
{
subscribers.Add(handler);
}
return handler;
}
/// <summary>
/// Publishes the specified message to all subscribers
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="message">The message.</param>
public void Publish<T>(T message) where T : class, IMessage
{
ExceptionFactory.ThrowIf(
message == null,
() => new ArgumentNullException(nameof(message), "You can not publish a null message."));
if (!listeners.ContainsKey(typeof(T)))
{
return;
}
foreach (INotification<T> handler in listeners[typeof(T)])
{
handler.ProcessMessage(message);
}
}
/// <summary>
/// Unsubscribes the specified handler by removing their handler from our collection.
/// </summary>
/// <typeparam name="T">The message Type you want to unsubscribe from</typeparam>
/// <param name="subscription">The subscription to unsubscribe.</param>
private void Unsubscribe(NotificationArgs args)
{
// If the key doesn't exist or has an empty collection we just return.
// We will leave the key in there for future subscriptions to use.
if (!listeners.ContainsKey(args.MessageType) || listeners[args.MessageType].Count == 0)
{
return;
}
// Remove the subscription from the collection associated with the key.
List<ISubscription> subscribers = listeners[args.MessageType];
lock (subscribers)
{
subscribers.Remove(args.Subscription);
}
args.Subscription.Unsubscribing -= this.Unsubscribe;
}
}
我订阅
/// <summary>
/// Provides a contract to Types wanting to subscribe to published messages
/// with conditions and a callback.
/// </summary>
public interface ISubscription
{
/// <summary>
/// Occurs when the subscription is being unsubscribed.
/// </summary>
event Action<NotificationArgs> Unsubscribing;
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ISubscription"/> is active.
/// </summary>
bool IsActive { get; }
/// <summary>
/// Unsubscribes the registerd callbacks from receiving notifications.
/// </summary>
/// <param name="notificationCenter">The notification center.</param>
void Unsubscribe();
}
INotification
using System;
/// <summary>
/// Processes a subscription message.
/// </summary>
/// <typeparam name="TMessageType">The type of the message type.</typeparam>
public interface INotification<TMessageType> : ISubscription where TMessageType : class, IMessage
{
/// <summary>
/// Registers the specified action for callback when a notification is fired for T.
/// </summary>
/// <param name="callback">The message being posted along with the subscription registered to receive the post.</param>
/// <returns></returns>
void Register(
Action<TMessageType, ISubscription> callback,
Func<TMessageType, bool> condition = null);
/// <summary>
/// Processes the message, invoking the registered callbacks if their conditions are met.
/// </summary>
/// <param name="message">The message.</param>
void ProcessMessage(TMessageType message);
}
IMessage
/// <summary>
/// Allows for receiving the content of a message
/// </summary>
public interface IMessage
{
/// <summary>
/// Gets the content.
/// </summary>
/// <returns>Returns the content of the message</returns>
object GetContent();
}
/// <summary>
/// Allows for receiving the content of a message
/// </summary>
/// <typeparam name="TContent">The type of the content.</typeparam>
public interface IMessage<TContent> : IMessage where TContent : class
{
/// <summary>
/// Gets the content of the message.
/// </summary>
TContent Content { get; }
}
WakeMeUpNotification
/// <summary>
/// Provides methods for dispatching notifications to subscription handlers
/// </summary>
/// <typeparam name="TMessageType">The type of the message type.</typeparam>
public class WakeMeUpNotification : IMessage<DateTime> where TContentType : class
{
public WakeMeUpNotification(DateTime timeToWakeUp)
{
this.Content = timeToWakeUp
}
/// <summary>
/// Gets the content of the message.
/// </summary>
public DateTime Content { get; protected set; }
/// <summary>
/// Gets the content of the message.
/// </summary>
public DateTime GetContent()
{
return this.Content;
}
/// <summary>
/// Gets the content.
/// </summary>
object IMessage.GetContent()
{
return this.GetContent();
}
}
StartMyTvNotification
/// <summary>
/// Provides methods for dispatching notifications to subscription handlers
/// </summary>
/// <typeparam name="TMessageType">The type of the message type.</typeparam>
public class StartMyTvNotification : IMessage<bool> where TContentType : class
{
public StartMyTvNotification(bool isOn)
{
this.Content = isOn;
}
/// <summary>
/// Gets the content of the message.
/// </summary>
public bool Content { get; protected set; }
/// <summary>
/// Gets the content of the message.
/// </summary>
public bool GetContent()
{
return this.Content;
}
/// <summary>
/// Gets the content.
/// </summary>
object IMessage.GetContent()
{
return this.GetContent();
}
}
通知
using System;
/// <summary>
/// Handles chat message subscriptions
/// </summary>
internal class Notification<TMessage> : INotification<TMessage> where TMessage : class, IMessage
{
/// <summary>
/// The callbacks invoked when the handler processes the messages.
/// </summary>
private Action<TMessage, ISubscription> callback;
/// <summary>
/// The conditions that must be met in order to fire the callbacks.
/// </summary>
private Func<TMessage, bool> condition;
/// <summary>
/// Occurs when the subscription is being unsubscribed.
/// </summary>
public event Action<NotificationArgs> Unsubscribing;
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ISubscription" /> is active.
/// </summary>
public bool IsActive { get; protected set; }
/// <summary>
/// Registers a callback for when a chat message is published by the MessageCenter
/// </summary>
/// <param name="processor">The message.</param>
/// <returns></returns>
public void Register(
Action<TMessage, ISubscription> processor,
Func<TMessage, bool> condition)
{
this.callback = processor;
this.condition = condition;
this.IsActive = true;
}
/// <summary>
/// Unsubscribes the handler from notifications. This cleans up all of the callback references and conditions.
/// </summary>
public void Unsubscribe()
{
this.callback = null;
this.condition = null;
try
{
this.OnUnsubscribing();
}
finally
{
this.IsActive = false;
}
}
/// <summary>
/// Processes the message by verifying the callbacks can be invoked, then invoking them.
/// </summary>
/// <param name="message">The message.</param>
public void ProcessMessage(TMessage message)
{
if (this.condition != null && !this.condition(message))
{
this.callback(message, this);
return;
}
this.callback(message, this);
}
/// <summary>
/// Called when the notification is being unsubscribed from.
/// </summary>
protected virtual void OnUnsubscribing()
{
var handler = this.Unsubscribing;
if (handler == null)
{
return;
}
handler(new NotificationArgs(this, typeof(TMessage)));
}
}
NotificationArgs
public class NotificationArgs
{
public NotificationArgs(ISubscription subscription, Type messageType)
{
this.Subscription = subscription;
this.MessageType = messageType;
}
public ISubscription Subscription { get; private set; }
public Type MessageType { get; private set; }
}