构造两个相互需要的对象 [英] Constructing two objects that need each other
问题描述
一个令人费解的架构问题:您有两个对称的类A
和B
.每个 A
/B
对象都可以使用 A 私下产生
/IA
/IB
类型的值.CreateIA()B.CreateIB()
方法.相反的类需要这些值 - A
需要 IB
而 B
需要 IA
.
A puzzling architectural question: You have two symmetrical classes A
and B
. Each A
/B
object may privately produce a value of type IA
/IB
using the A.CreateIA()
/B.CreateIB()
methods. These values are needed by the opposite classes - A
needs IB
and B
needs IA
.
目标是编写PairMaker.MakePair()
函数,该函数构建一对A
和B
对象的互连.您还必须为 A
和 B
类编写适当的构造函数.A
和 B
类在不同的程序集中并且看不到彼此的内部结构.链接应该是安全的——外部代码不应该能够访问或修改对象字段.您可以根据需要编写其他类并将任何方法添加到 A
和 B
- 只是不要破坏链接的安全性.
The goal is to write the PairMaker.MakePair()
function that constructs an interlinks a pair of A
and B
objects. You also have to write appropriate constructors for the A
and B
classes. A
and B
classes are in different assemblies and don't see each other's internals. The link should be secure - the external code should not be able to access or modify the object fields. You can write additional classes and add any methods to A
and B
as needed - just don't break the security of the link.
interface IA { }
interface IB { }
class A {
IB ib;
//Some constructor
//Other members
IA CreateIA() { }
}
class B {
IA ia;
//Some constructor
//Other members
IB CreateIB() { }
}
class PairMaker {
public static Tuple<A, B> MakePair() {
//What's here?
}
}
这个问题类似于如何构造两个对象,彼此作为参数/成员,但这个问题没有得到正确回答.
This question is similar to How to construct two objects, with each other as a parameter/member, but that question wasn't answered properly.
推荐答案
这是一个可能的解决方案.我不喜欢它的外观(我讨厌构造函数中的那些 out
参数).
Here is a possible solution. I don't like how it looks (I hate those out
parameters in the constructors).
class A {
IB _ib;
public A(out Func<IA> getter, out Action<IB> setter) {
getter = CreateIA;
setter = SetIB;
}
void SetIB(IB ib) {
_ib = ib;
}
IA CreateIA() { throw new NotImplementedException(); }
}
class B {
IA _ia;
public B(out Func<IB> getter, out Action<IA> setter) {
getter = CreateIB;
setter = SetIA;
}
void SetIA(IA ia) {
_ia = ia;
}
IB CreateIB() { throw new NotImplementedException(); }
}
.
class PairMaker {
public static Tuple<A, B> MakePair() {
Func<IA> iaGetter;
Func<IB> ibGetter;
Action<IA> iaSetter;
Action<IB> ibSetter;
A a = new A(out iaGetter, out ibSetter);
B b = new B(out ibGetter, out iaSetter);
iaSetter(iaGetter());
ibSetter(ibGetter());
return Tuple.Create(a, b);
}
}
这篇关于构造两个相互需要的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!