Java:限制对复合类(接口和组合)方法的访问
因此,我有两个类(ProductOne和ProductTwo),它们继承自一个基本抽象类(BaseProduct)。 基本抽象类依次创建另一个类(Account)的对象 现在,我想限制对ProductOne对象的Account类的一些方法的访问,并类似地限制对ProductTwo对象的其他一些方法的访问Java:限制对复合类(接口和组合)方法的访问,java,interface,composition,Java,Interface,Composition,因此,我有两个类(ProductOne和ProductTwo),它们继承自一个基本抽象类(BaseProduct)。 基本抽象类依次创建另一个类(Account)的对象 现在,我想限制对ProductOne对象的Account类的一些方法的访问,并类似地限制对ProductTwo对象的其他一些方法的访问 我认为我需要创建Account类作为接口/抽象类,并为其创建不同的实现。这种理解正确吗?你能告诉我具体怎么做吗?看来你这里有两行产品概念。您可以做的是将BaseProduct和Account抽象
我认为我需要创建Account类作为接口/抽象类,并为其创建不同的实现。这种理解正确吗?你能告诉我具体怎么做吗?看来你这里有两行产品概念。您可以做的是将
BaseProduct
和Account
抽象并使用泛型
@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
}
这样,编译时以下两项都将失败:
也许这就是你要找的您可以使用
isinstance
检查正确的实例或使用访问者模式。不过,我确实认为,如果您制作了一个使用多态性的解决方案,并简单地注入正确的符合帐户的依赖项,而不是为此使用基类,那就更好了。就我的2c
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();
}
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()