gpt4 book ai didi

design-patterns - 耦合度太高-如何更好地设计此类?

转载 作者:行者123 更新时间:2023-12-04 05:11:20 26 4
gpt4 key购买 nike

在我的代码上运行FxCop,我得到以下警告:

Microsoft.Maintainability : 'FooBar.ctor is coupled with 99 different types from 9 different namespaces. Rewrite or refactor the method to decrease its class coupling, or consider moving the method to one of the other types it is tightly coupled with. A class coupling above 40 indicates poor maintainability, a class coupling between 40 and 30 indicates moderate maintainability, and a class coupling below 30 indicates good maintainability.



我的类(class)是所有来自服务器的消息的登陆区。服务器可以向我们发送不同EventArgs类型的消息:
public FooBar()
{
var messageHandlers = new Dictionary<Type, Action<EventArgs>>();
messageHandlers.Add(typeof(YouHaveBeenLoggedOutEventArgs), HandleSignOut);
messageHandlers.Add(typeof(TestConnectionEventArgs), HandleConnectionTest);
// ... etc for 90 other types
}

“HandleSignOut”和“HandleConnectionTest”方法中几乎没有代码。他们通常将工作传递给另一个类中的函数。

如何在降低耦合的情况下使此类更好?

最佳答案

让负责工作的类(class)注册他们感兴趣的事件... event broker模式。

class EventBroker {
private Dictionary<Type, Action<EventArgs>> messageHandlers;

void Register<T>(Action<EventArgs> subscriber) where T:EventArgs {
// may have to combine delegates if more than 1 listener
messageHandlers[typeof(T)] = subscriber;
}

void Send<T>(T e) where T:EventArgs {
var d = messageHandlers[typeof(T)];
if (d != null) {
d(e);
}
}
}

关于design-patterns - 耦合度太高-如何更好地设计此类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/189156/

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