我有几个解决方案,所有解决方案都围绕使用私有单例实例作为“密钥”来证明调用者就是他们所说的那个人。
解决方案1:朋友类是单例
public class A
{
private underwear myUnderwear;
public ChangeUnderwear(B friend, underwear newUnderwear)
{
if (friend == null) return;
myUnderwear = newUnderwear
}
}
public sealed class B
{
private B() {};
private B inst;
private MessWithA(A a)
{
a.ChangeUnderwear(this, new Thong());
}
}
有人看到那里有任何缺陷吗?当你有一个 Foo 类和一个 FooManager 单例时,这种技术会起作用。
解决方案 2:
如果朋友不是单例,我想你可以使用隐藏构造和隐藏所有实例的相同想法:
interface IB
{ ... }
public sealed class B : IB
{
private B() {};
public IB CreateB()
{
return (IB)new B();
}
private MessWithA(A a)
{
a.ChangeUnderwear(this, new Thong());
}
}
但是现在您需要某种方法来防止敌人简单地将 IB 转换为 B,然后冒充 B 访问 A 的仅限朋友的成员。有什么想法吗?
解决方案 3:单例类让它的实例由第一个请求它的调用者拥有。朋友类试图在启动时抓取实例,如果其他人先抓取它就会发脾气
public class A
{
private underwear myUnderwear;
public ChangeUnderwear(B.IdCard friend, underwear newUnderwear)
{
if (friend == null) return;
myUnderwear = newUnderwear
}
}
public class B
{
public sealed class IdCard
{
private IdCard() {};
private static bool created = false;
public IDCard GetId()
{
if (created) throw new Exception("Why are two people asking for the same ID?!?");
created = true;
return new IDCard();
}
}
private static IdCard id;
static B()
{
id = IDCard.CreateId();
if (id == false) throw new Tantrum("Panic: Someone stole my ID card before I could grab it");
}
private void MessWithA(A a)
{
a.ChangeUnderwear(id, new Thong());
}
}