存储“绝对异或增量”的设计模式价值
在应用程序数据输入中,我允许用户插入一个可以代表两个不同事物的数值:
- 一个绝对值,例如 5,这意味着属性 P 应该分配值 5;
- 一个相对值,例如 +5,这意味着属性 P 应增加 5
我的问题是:使用哪种数据结构来存储此信息? 我提出了一些替代方案。 我的想法与第三个想法一致,但我想知道该模式是否“正确”。
1) 这里分配增量的绝对异或,另一个留空。不太令人满意。
class DoubleFieldBased {
Integer absolute;
Integer increment;
}
2) 这里,值的“magnitude”被保存到“value”中,而布尔值“increment”则告诉该值是绝对值还是相对值。甚至不太令人满意。
class FieldAndBoolean {
Integer value;
boolean increment;
}
3)这里我将焦点转移到 applyValue 方法上,该方法使用多态性并根据“我是哪个类”的隐式信息做正确的事情。令人满意,但有点复杂,我怀疑该模式并不完美。
public static abstract class AbstractValue {
int myvalue;
public AbstractValue (int myvalue) {this.myvalue = myvalue;}
public abstract int applyValue (int value);
}
public static class Absolute extends AbstractValue {
public Absolute (int myvalue) {super(myvalue);}
public int applyValue (int value) {
return value;
}
}
public static class Incremental extends AbstractValue {
public Incremental (int myvalue) {super(myvalue);}
public int applyValue(int value) {
return myvalue + value;
}
}
In a application data entry, I allow the user to insert a numeric value that can represent two different things:
- an absolute value, say 5, meaning that a property P should be assigned the value 5
- a relative value, say +5, meaning that the property P should be incremented by 5
My question is: which data-structure use to store this inforation?
I lay down some alternatives.
My idea is going with the 3rd idea, but I wonder is the pattern is "correct".
1)
Here the absolute xor the increment is assigned, the other left null. Not very satisfactory.
class DoubleFieldBased {
Integer absolute;
Integer increment;
}
2)
Here the "magnitude" of the value is saved into "value", while the boolean "increment" tells wheter the value is absolute or relative. Even less satisfactory.
class FieldAndBoolean {
Integer value;
boolean increment;
}
3)Here I move the focus to the method applyValue, that uses polymorphism and do the right thing based on the implicit information of what class "am I". Satisfactory but a bit complex, and I suspect the pattern isn't perfect.
public static abstract class AbstractValue {
int myvalue;
public AbstractValue (int myvalue) {this.myvalue = myvalue;}
public abstract int applyValue (int value);
}
public static class Absolute extends AbstractValue {
public Absolute (int myvalue) {super(myvalue);}
public int applyValue (int value) {
return value;
}
}
public static class Incremental extends AbstractValue {
public Incremental (int myvalue) {super(myvalue);}
public int applyValue(int value) {
return myvalue + value;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想说使用整数或其他数字类型)和枚举,如下所示:
您甚至可以使用枚举作为策略:
I'd say use an Integer or other numeric type) and an enum, something like this:
You could even use the enum as strategy: