2016-09-24 24 views
0

我真的很努力想出一个我正在构建的警报器的设计模式。下面是我试图做的一个人为的例子:警报器的设计模式

一个人想要通过天气类型(雨,雪,太阳等)获得警报。一个人也可以选择警报方式(电子邮件,短信,闲暇频道,时尚聊天室等)

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

这里是我的基本轮廓,但看起来它应该做的 “更好”:

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; 
      } 
     } 
    } 
} 
+0

如果你需要讨论一个算法或设计模式,你可能应该把问题发布给程序员.stackexchange.com – Steve

+2

@Steve在引用其他网站时,指出[交叉发布是皱眉了](http://meta.stackexchange.com/tags/cross-posting/info) – gnat

+0

@gnat绝对正确,我的错在这里,但我是如此从程序员看到的一个meta post被拿走,我已经完全忘记 – Steve

回答

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); 
     } 
    } 
} 

您也可以替换与其他通用类型的天气类型。

+0

难道你没有得到基于需要被解雇的警报类型(电子邮件,短信等),坚持做一个大的switch语句? – Matt

1

这听起来像是发布&订阅模式。有许多方式可以实现所说的模式,这里有一个链接到您开始使用(当然你决定哪个最适合你之前,先看看其他人): https://msdn.microsoft.com/en-us/library/ms752254(v=vs.110).aspx

你可能对夫妇它与一个事件聚合器 - https://msdn.microsoft.com/en-us/library/ff921122.aspx

+0

你可能是对的,但我不确定如何修改上面的代码 - 是不是已经发布给订阅者? – Matt

+0

是的,它似乎确实正在发布到您的订户列表。但要完成这种模式,您可能希望将事件提升/收听与您当前的提醒器分开。以下是我发现的更详细的示例:http://www.codeproject.com/Articles/866547/Publisher-Subscriber-pattern-with-Event-Delegate-a –