构建需要对方两个对象 [英] Constructing two objects that need each other
问题描述
一个令人费解的问题建筑:你有两个对称的类 A
和 B
。每个 A
/ B
对象可以私下生产类型的值 IA
/ 使用IB
的 A.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
.
我们的目标是为编写构造一个互连有一对 A $ C $的
。您也可以写的 PairMaker.MakePair()
功能C>和 B
对象 A
和 B
类的适当的构造。 A
和 B
类在不同的组件并没有看到对方的内部结构。这个连接应该是安全的 - 外部code应该不能访问或修改的对象字段。你可以写其他类和添加任何方法 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?
}
}
这个问题是类似<一个href=\"http://stackoverflow.com/questions/371708/how-to-construct-two-objects-with-each-other-as-a-parameter-member\">How构建两个对象,彼此作为一个参数/成员,但这个问题没有正确答案。
This question is similar to How to construct two objects, with each other as a parameter/member, but that question wasn't answered properly.
更新:请注意,这个问题的是可解(你可以写上你想要的任何构造函数)。请不要downvote或关闭这个问题,只是因为你不能想出一个解决方案。
Update: Please note, that this problem IS solvable (as you can write any constructors you want). Please don't downvote or close this question just because you cannot devise a solution.
推荐答案
下面是一个可能的解决方案。我不喜欢它的外观(我讨厌那些退出
参数的构造函数)。
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屋!