如果你想这样做,你需要一个对象,它只能在A层中定义,并且是B层需要的key 。 Layer C 也是一样的:只能通过提供 key(一个对象)来访问它,该密钥只能从 Layer B创建>.
这是我刚刚创建的代码,它向您展示了如何使用 3 个类来实现这个想法:
A 类:
public class A
{
/* only A can create an instance of AKey */
public final class AKey
{
private AKey() {
}
}
public A() {
B b = new B(new AKey());
b.f();
}
}
B 类:
public class B
{
/* only B can create an instance of BKey */
public final class BKey
{
private BKey() {
}
}
/* B wants an instance of AKey, and only A can create it */
public B(A.AKey key) {
if (key == null)
throw new IllegalArgumentException();
C c = new C(new BKey());
c.g();
}
public void f() {
System.out.println("I'm a method of B");
}
}
C 类:
public class C
{
/* C wants an instance of BKey, and only B can create it */
public C(B.BKey key) {
if (key == null)
throw new IllegalArgumentException();
}
public void g() {
System.out.println("I'm a method of C");
}
}
现在,如果您想将此行为扩展到特定的层,您可以如下所示进行:
A 层:
public abstract class AbstractA
{
/* only SUBCLASSES can create an instance of AKey */
public final class AKey
{
protected AKey() {
}
}
}
public class A extends AbstractA
{
public A() {
B b = new B(new AKey());
b.f();
BB bb = new BB(new AKey());
bb.f();
}
}
public class AA extends AbstractA
{
public AA() {
B b = new B(new AKey());
b.f();
BB bb = new BB(new AKey());
bb.f();
}
}
B 层:
public abstract class AbstractB
{
/* only SUBCLASSES can create an instance of BKey */
public final class BKey
{
protected BKey() {
}
}
}
public class B extends AbstractB
{
/* B wants an instance of AKey, and only A Layer can create it */
public B(AbstractA.AKey key) {
if (key == null)
throw new IllegalArgumentException();
C c = new C(new BKey());
c.g();
CC cc = new CC(new BKey());
cc.g();
}
public void f() {
System.out.println("I'm a method of B");
}
}
public class BB extends AbstractB
{
/* BB wants an instance of AKey, and only A Layer can create it */
public BB(AbstractA.AKey key) {
if (key == null)
throw new IllegalArgumentException();
C c = new C(new BKey());
c.g();
CC cc = new CC(new BKey());
cc.g();
}
public void f() {
System.out.println("I'm a method of BB");
}
}
C 层:
public class C
{
/* C wants an instance of BKey, and only B Layer can create it */
public C(B.BKey key) {
if (key == null)
throw new IllegalArgumentException();
}
public void g() {
System.out.println("I'm a method of C");
}
}
public class CC
{
/* CC wants an instance of BKey, and only B Layer can create it */
public CC(B.BKey key) {
if (key == null)
throw new IllegalArgumentException();
}
public void g() {
System.out.println("I'm a method of CC");
}
}
每一层都以此类推。