【问题标题】:Which design pattern for an alerter警报器的设计模式
【发布时间】:2016-09-25 03:05:27
【问题描述】:

我真的很难为我正在构建的警报器提出设计模式。这是我正在尝试做的一个人为的例子:

一个人想要根据天气类型(雨、雪、太阳等)获得警报。一个人还可以选择警报方法(电子邮件、短信、slack 频道、hipchat 房间等)

我需要:有一个接受天气类型的课程。然后它检索所有关心该天气类型的人。然后它遍历所有人并向他们发送他们的警报(基于人的警报类型偏好)。

这是我的基本大纲,但似乎应该做得“更好”:

public class Alerter
{
    private readonly WeatherType _weatherType;

    public Alerter(WeatherType weatherType)
    {
        _weatherType = weatherType;
    }

    public void SendAlerts()
    {
        var people = PersonRepository.GetPeople(_weatherType);

        foreach (Person person in people)
        {
            switch (person.AlertType)
            {
                case Email:
                    var e = new EmailAlerter();
                    e.SendToPerson(person, _weatherType);
                    return;
                case SMS:
                    var s = new SmsAlerter();
                    s.SendToPerson(person, _weatherType);
                    return;
            }
        }
    }
}

【问题讨论】:

  • 如果您需要讨论算法或设计模式,您应该将问题发布到programmers.stackexchange.com
  • @Steve 在引用其他网站时,指出cross-posting is frowned upon 通常会有所帮助
  • @gnat 绝对正确,这是我的错,但我被一篇关于程序员的元帖子带走了,以至于我完全忘记了
  • 我已投票结束,我已在程序员中发帖:programmers.stackexchange.com/questions/331915/…

标签: c# design-patterns


【解决方案1】:

您可以使用generics

像这样:

public class Alerter<T>
{
    private readonly WeatherType _weatherType;

    public Alerter(WeatherType weatherType)
    {
        _weatherType = weatherType;
    }

    public void SendAlerts()
    {
        var people = PersonRepository.GetPeople(_weatherType);

        foreach (Person person in people)
        {
            var e = (T)Activator.CreateInstance(typeof(T));
            e.SendToPerson(person, _weatherType);
        }
    }
}

您还可以将天气类型替换为其他通用类型。

【讨论】:

  • 根据需要触发的警报类型(电子邮件、短信等),您不会被大开关语句卡住吗?
【解决方案2】:

这听起来像是发布和订阅模式。有很多方法可以实现上述模式,这里有一个链接让你开始(但在你决定哪种最适合你之前,一定要看看其他人): https://msdn.microsoft.com/en-us/library/ms752254(v=vs.110).aspx

您可以将它与事件聚合器结合使用 - https://msdn.microsoft.com/en-us/library/ff921122.aspx

【讨论】:

  • 您可能是对的,但我不确定如何将上面的代码调整到其中 - 它不是已经向订阅者发布了吗?
  • 是的,它似乎正在发布到您的订阅者列表中。但是要完成该模式,您可能希望将事件引发/侦听与当前警报器分开。这是我找到的更详细的示例:codeproject.com/Articles/866547/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多