不同对象之间共享对象
我遇到的情况是,我有一个公共引用对象作为参数传递给不同的操作对象。传递它会使代码变得非常混乱。 有没有办法让它像对每个操作(如会话)的引用?然而,它只是一个核心代码库。使用静态类不是解决方案。
谢谢
I am having a situation that I have a common reference object that is being pass around as parameter to different operation object. It makes the code very messy to pass it around.
Is there anyway to make it like a reference to every operation (like a session)? However, it is just a core code library. Using static class is not the solution.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
解决方案 1 - 您可以使用单例。它们保证运行代码中只有该类的一个实例。
解决方案 2 - 为什么不将共享引用对象作为具有这些操作的对象的属性?这样,每个操作都可以访问它。您可以做一些奇特的事情,例如如果引用属性为 null,则抛出异常等。
Solution 1 - You can use singletons. They guarantee that there is only one instance of the class in the running code.
Solution 2 - why don't you put the shared reference object as a property of the object with those operations? That way, each operation has access to it. You can do some fancy stuff like if the reference property is null, throw an exception or so.
据我所知,有两种通用方法:
a) 使用 IoC 和构造函数依赖项来传递共享对象。正如您所提到的,如果这个对象在很多很多地方使用,这会污染界面,并且在很多情况下会增加很多混乱。
b) 使用环境上下文:创建基于接口的单例可以由需要对象实例的类访问。在单例中有一个设置器,允许您覆盖实例(例如用于单元测试),因此仍然可以测试代码。
There are two general approaches to this that I know of:
a) Use IoC and a constructor dependency to pass in your shared object. As you mentioned if this object is used in many, many places this pollutes the interface and in many cases adds a lot of clutter.
b) Use an ambient context: Create a interface based singleton that may be accessed by the classes that need the object instance. Have a setter within the singleton that allows you to override the instance (e.g. for unit testing) so testing the code is still possible.
也许环境上下文模式适合您? http://aabs.wordpress。 com/2007/12/31/the-ambient-context-design-pattern-in-net/
Maybe the Ambient Context Pattern could work for you? http://aabs.wordpress.com/2007/12/31/the-ambient-context-design-pattern-in-net/