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

我有2节课

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与私有构造函数一起使用,这是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/

10-10 01:49