c# - 这是观察者反模式吗? (有奖金状态机问题)

标签 c# events design-patterns observer-pattern anti-patterns

我想知道以下是否是对观察者模式的错误使用。我知道主体应该是一个,而听众应该是多个。但是,我的应用程序中的主题最终可能比听众更多!

玩家

Form1:不言自明
DocumentCreator:包含工厂方法和从列表中选择文件的策略
文档:包含有关文档文件和子级模板方法的信息

建议

IErrorProne:上述玩家实现事件的接口(interface),将他们变成主题 报告:监听 IErrorProne 对象并处理日志记录/电子邮件
DocumentState:这是一个我有点不确定的奖励。我还没有完全确定模板之外的良好流程。目前我在 Document 类中有一个状态机。我想将状态机从 Document 类中拉出并放入 Form1 中,从而将两者相互解耦。

public interface IErrorProne
{
    public delegate void ErrorEventDelegate(
        object sender, 
        ErrorEventArgs e
        );

    public event ErrorEventDelegate ReportError;
}

public abstract class Document : IDisposable, IErrorProne // My Template
{
    public void Process()
    {
        //Error Occured
        OnReportError(); // safely triggers error reporting
    }
}

public class Reporting
{
    static Reporting instance = new Reporting();

    public void HandleError(object sender, ErrorEventArgs e);
}

public partial class Form1 
{
    private DocumentCreator docFactory 
                                = new DocumentCreator(new RandomPicking());
    private Document theDoc     = null;
    private Reporting reporting = Reporting.Instance;
    private DocState state      = new InitialState(); 
    //DocState not in this example but demonstrates how it might work

    public Form1()
    {
        docFactory.ReportError += reporting.HandleError;
        theDoc.ReportError     += reporting.HandleError;

        docFactory.ReportError += state.HandleError;
        theDoc.ReportError     += state.HandleError;
    }

    void BackgroundWork(...)
    {
        using (theDoc = DocumentFactory.Instance.CreateDocument())
        {
           if (theDoc != null)
               theDoc.Process();
        }
    }
}

我想我的问题是,如果我有一个多对一,而不是一对多,那么它是一个反模式?

最佳答案

如果您将其视为发布-订阅,那么这确实无关紧要。如果您采用领域事件样式,则可以让任何事物和任意数量的事物发布任何给定的领域事件,并且让任何事物和任意数量的事物订阅领域事件。

许多->许多、许多->一、一->许多都是有效的。

关于c# - 这是观察者反模式吗? (有奖金状态机问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4761383/

相关文章:

c# - Linq 查询返回父子的扁平化列表

events - 正确的 Google Analytics 事件跟踪语法是什么?

c++ - 在变量中存储异构类类型

c# - .NET 框架 : Random number generator produces repeating pattern

c# - Byte Vigenere Cipher,解密错误

c# - 检查事件是否至少被触发一次

asp.net-mvc - 使用 ASP.NET MVC 和 MVVM 的页面初始化模式(如 knockoutjs)

unit-testing - 编写通常只公开一个公共(public)方法的类是一种好习惯吗?

c# - 使用依赖注入(inject)在构造函数之外创建类的新实例

events - 两个不同元素的提交和点击事件由同一个 jquery 函数处理?