java - 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 类并为其创建不同的实现。这种理解正确吗?你能告诉我该怎么做吗?
解决方案
看来您在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
并让它们在实际的“类型一”和“类型二”类中实现:methodTwo
Account
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()
推荐阅读
- twig - 如何在错误页面中访问自定义树枝扩展
- arrays - React native 未正确创建链接以进行搜索
- javascript - 使用 setTimeout(fn, 0) 和不使用的区别
- c# - 如何在mvc中上传图片时添加水印标志
- microsoft-graph-api - 不再支持 ChannelMessage.Read.All 的应用程序权限?
- autodesk-forge - 在伪造查看器 onSelectionEvent 中,当在移动设备上打开网站时,this.viewer.getProperties() 方法不返回属性信息
- javascript - 在 datepicker 中设置 minDate 和 maxDate
- java - 如何解决 IllegalArgumentException:目标对象不能为空
- javascript - 包 react-native-onesignal 已被忽略,因为它包含无效配置
- r - 尝试在 MacOS 上的 R 中安装 devtools 时出现非零退出状态