我有一系列属性,这些属性要么应用到我的对象,要么不应用到我的对象:
EVEN
ODD
POSITIVE
NEGATIVE
NEGATIVE_AND_ODD
并且它们中的每一个都适用于对象当且仅当某些逻辑语句成立,即
EVEN iff num%2==0
ODD iff num%2!=0
POSITIVE iff num>0
NEGATIVE iff num<0
NEGATIVE_AND_ODD iff num < 0 and num%2==0
我有大量这些属性,并且可以随时添加新属性。属性彼此之间没有依赖关系,也不应该创建这样的依赖关系。
我需要一个方案,以便我的主类可以执行以下操作:
Go through the list of attributes
If this attribute fits its required logical predicate, then
add the attribute to my object
您会使用什么类型的工具来实现此目的?
最佳答案
你可以尝试这样的事情
interface Attribute
{
public boolean matches(boolean someBoolean, int num);
}
然后实现每个属性,例如
class Even implements Attribute
{
public boolean matches(boolean someBoolean, int num)
{
// someBoolean is not important to this attribute
// but it may be in others
return num%2==0;
}
}
然后你可以创建一个 Attribute
数组(或列表或其他),然后循环它们。
关于Java - 将属性与逻辑介词相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9900024/