Java:限制对复合方法的访问class(接口和组合)

Java: Limit access to methods of a composite class (Interface and Composition)

@Getter
public abstract class BaseProduct {
    Account account = new Account();
}

public class ProductOne extends BaseProduct {
    FieldOne fieldOne = new FieldOne();
}

public class ProductTwo extends BaseProduct {
    FieldTwo fieldTwo = new FieldTwo();
}

public class Account {
    public TypeOne methodOne() {
        return typeOne;
    }

    public TypeTwo methodTwo() {
        return typeTwo;
    }
}

public class MyClass {

    ProductOne productOne = new ProductOne();
    productOne.getAccount().methodOne();    //accessible
    productOne.getAccount().methodTwo();    //not accessible (error)

    ProductTwo productTwo = new ProductTwo();
    productTwo.getAccount().methodOne();    //not accessible (error)
    productTwo.getAccount().methodTwo();    //accessible
}

所以,我有两个 classes(ProductOne 和 ProductTwo)继承自 Base Abstract class(BaseProduct)。 Base Abstract class 依次创建另一个 class (Account)

的对象

现在我想限制对 ProductOne 对象的某些帐户 class 方法的访问,并类似地限制对 ProductTwo 对象的某些其他方法的访问。

我想我需要将帐户 class 创建为 Interface/Abstract class 并为其创建不同的实现。这种理解是否正确?你能告诉我具体怎么做吗?

看来你这里有两行Product概念。您可以做的是将 BaseProductAccount 都抽象化并使用泛型。

public abstract class BaseProduct<A extends Account> {
    public abstract A getAccount();
}

class ProductOne extends BaseProduct<TypeOneAccount> {
    FieldOne fieldOne = new FieldOne();
}

class ProductTwo extends BaseProduct<TypeTwoAccount> {
    FieldTwo fieldTwo = new FieldTwo();
}

这将允许具体 "product" 类型绑定到特定 Account 类型。

然后,从 Account 中删除 methodOnemethodTwo 并在实际 "type one" 和 "type two" 中实现它们 类:

public abstract class Account {
}

public class TypeOneAccount extends Account {
    public TypeOne methodOne() {
        return typeOne;
    }
}

public class TypeTwoAccount extends Account {
    public TypeTwo methodTwo() {
        return typeTwo;
    }
}

有了这个,以下两个都将在编译时失败

//fails because productOne.getAccount() returns a TypeOneAccount object,
//which doesn't have methodTwo()
productOne.getAccount().methodTwo()

//fails because productTwo.getAccount() returns a TypeTwoAccount object,
//which doesn't have methodOne()
productTwo.getAccount().methodOne()