gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:41:34 24 4
gpt4 key购买 nike

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

球员

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

提议

IErrorProne:上面的player实现一个事件的接口(interface),将他们变成subject报告:监听 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();
}
}
}

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

最佳答案

如果你把它看成是发布-订阅,那就真的无所谓了。如果您采用领域事件风格,您可以让任何事物和任意数量的事物发布任何给定的领域事件,以及任何事物和任意数量的事物订阅领域事件。

Many->Many, many->one, one->Many 都是有效的。

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com