I have property file(key/value) pair from where I currently read a value against a key and display that value as it is in the UI .
The complexity have increased,Now the value is more dynamic based on some formula. The formula includes a variable parameter whose value I will get at run time.
Is there any java design pattern to design this scenario .
I was thinking to put a method name in the property file against a key.
Now I will read the key and fetch the method name . This method will calculate the value for that particular key.
Please let me know your suggestion
Is there any java design pattern to design this scenario .
I don't know if there is a pattern.
If I understand your question right I can explain what I do usually.
#number#
Little example:
messages.properties
name.of.key = sum of #0# + #1# = #2#
Then I read the value from and replace the #num#
with appropiated values (NOTE: here is in the same method for shortenes, but I use an external replace
method):
public void printSum(int n1, int n2) {
String myString = messageSource("name.of.key", Locale.getDefault(), null, null));
myString.replace("#0#", String.valueOf(n1));
myString.replace("#1#", String.valueOf(n2));
myString.replace("#2#", String.valueOf(n1+n2));
System.out.println(myString);
}
OUTPUT printSum(1,2);
sum of 1 + 2 = 3
Looks like the ANTLR would make here a great fit.
It is a parser generator. You give it grammar as an input and in return it provides you with a parser.
You can use the parser to transform the textual formula into a parsed tree representation. After that, you can run a visitor to evaluate each of the nodes. You just write some simple function to implement the behavior, such as:
public Double visitAdd(AntlrNode left, AntlrNode right) {
Double left = visit(left);
Double right = viist(right);
return left + right;
}
The grammar is very close to the familiar BNF notation. You just describe how your formula strings are. For example:
formula : left '+' right;
left: Number;
right: Number;
Number: [0-9]+;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With