gpt4 book ai didi

java - 如何避免从外部世界创建 B 类对象,并只允许通过 A 类

转载 作者:行者123 更新时间:2023-12-01 19:02:06 25 4
gpt4 key购买 nike

如何避免从外部世界创建 B 类对象,而只允许通过 A 类?

我有两个类

public class A {
B obj = null;
public A() {
obj = new B();
}
public void methodA () {
obj.methodB();
}
// other methods
}

public class B {
public void methodB () {
// some logic
}
//other methods
}

public class Client {
public static void main (String s[]) {
// Valid Call
A obj = new A();
obj.methodA(); // Since methodB is called internally

// Invalid Call , How to restrict this B object creation here ?
B objB = new B();
objB.methodB();

}
}

最佳答案

我能想到的一个解决方案是使用 A 的内部静态类:KeyToB 和私有(private)构造函数,B 需要实例化该类。因此,只有 A 可以实例化 B,B 可以位于不同的文件中。

public class A {
B obj = null;
public A() {
obj = new B(instance);
}
public void methodA() {
obj.methodB();
}
// other methods ..

//The key to have the right to instanciate B, only visible in A
private static KeyToB instance = new KeyToB();

public static class KeyToB{
private KeyToB() {
}
}
}

public class B {
//The constructor is package visible, it need a non null instance of KeyToB . If someone use new B(null), it will get a RuntimeException
B(KeyToB instance) {
if (instance == null){
throw new IllegalArgumentException("B can only be instanciated by A");
}
}
public void methodB() {
}
}

关于java - 如何避免从外部世界创建 B 类对象,并只允许通过 A 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11859430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com