如何处理OO应用程序中的跨领域问题?使用Singleton?依赖注入?什么? [英] How to deal with cross-cutting concerns in a OO Application? Use Singleton? Dependency Injection? What?

查看:142
本文介绍了如何处理OO应用程序中的跨领域问题?使用Singleton?依赖注入?什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在设计一个应用程序,我需要使用全局计时系统(这是一个跨领域的问题)。我需要从我的应用程序的任何地方访问来自该全球计时系统的数据,并且我不能看到应用程序的这部分需要它而另一部分不需要。

Let's say that I'm currently designing an application where I will need to use a global timing system (it's a cross-cutting concern). I'll need to access data from that global timing system from basically anywhere in my app and it's not like I can see that "this part of the application will need it while the other won't".

我的问题是..我应该将其设计为一种环境上下文(在本例中为Singleton),还是应该尝试设计其他方式来适应这种情况?

My question is.. should I design that as a kind Ambient Context (in this case, Singleton), or should I try to devise other way to accomodate for this?

我当然认为让我的所有类都必须通过构造函数注入将这个全局计时类传递给它们是不正确的。很多时候我必须将参考文件真正传递到链中,直到某些类最终需要它。另一方面,从阅读的角度来看,它会使一切变得更加清晰(它清楚地说明了我的课程的依赖性)。

I certainly don't feel it's correct to make all my classes have to get this global timing class passed to them by constructor injection. Lot's of time I would have to pass the reference really down the chain until some class eventually needs it. On the other hand, it would turn everything more clear from the reading stand point(it makes it clear what my classes' dependencies are).

人们通常如何处理这个?有没有其他技术可以帮助解决这个问题? AOP可能吗?

How do people generally deal with this? Are there any other techniques around that can help with this? AOP maybe?

PS:全球计时系统只是我从一本我正在阅读的书中获取的一个想法。记录系统将是这类问题的另一个很好的例子。

PS: The global timing system was just an idea I took from a book I'm currently reading. A logging system would be another good example of this kind of problem.

谢谢

推荐答案

如你所知,面向方面编程(AOP)的设计与考虑到这一点,我肯定会检查出来。

As you suggest, Aspect Oriented Programming (AOP) is designed with just this sort of thing in mind, so I'd certainly check that out.

虽然构造函数注入在这种情况下似乎很麻烦,但使用 IOC容器可能有助于减轻您的痛苦。单身似乎很适合这个账单,但是由于静态性,它们带来了可测性问题 - 但你可以通过将其分成两部分来解决这个问题。

While constructor injection does seem a hassle in this scenario, using an IOC container might help reduce your pain a bit. A singleton does seem to fit the bill well, but they bring issues with testability due to the staticness - but you can get round this by splitting it into two.

这篇关于如何处理OO应用程序中的跨领域问题?使用Singleton?依赖注入?什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆