首页 > 解决方案 > Java:限制对复合类方法的访问(接口和组合)

问题描述

@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
}

所以,我有两个类(ProductOne 和 ProductTwo),它们继承自基本抽象类(BaseProduct)。Base Abstract 类依次创建另一个类(Account)的对象

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

我想我需要将 Account 类创建为 Interface/Abstract 类并为其创建不同的实现。这种理解正确吗?你能告诉我该怎么做吗?

标签: javainterfacecomposition

解决方案


看来您在Product这里有两行概念。你可以做的是同时BaseProduct抽象Account和使用泛型。

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();
}

这将允许将具体的“产品”类型绑定到特定Account类型。

然后,删除methodOne并让它们在实际的“类型一”和“类型二”类中实现:methodTwoAccount

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()

推荐阅读