Reputation: 53806
I have a configuration file in following format :
item1=true
value=test
item2=false
pseudocode in app logic :
if(item1)
{
do something
}
else {
do something else
}
if(item2)
{
do something
}
else {
do something else
}
Is there pattern to handle this kind of configuration ? So instead of conditional statements use something else ?
Upvotes: 2
Views: 2100
Reputation: 5785
Depending on your specific needs, maybe you'll consider using "Feature Toggle": http://martinfowler.com/bliki/FeatureToggle.html or http://www.togglz.org/
Upvotes: 2
Reputation: 115328
You can use command pattern. First you can create command per option found in configuration file. Factory pattern is the best to do this. Tour factory can create a collection of commands. Then run these commands in loop.
The factory can be implemented using enum
:
public enum CommmandFactory {
item1 {
@Override
public ConfCommand create(String value) {
return new ItemOneCmd(value);
}
},
item2 {
@Override
public ConfCommand create(String value) {
return new ItemTwoCmd(value);
}
},
public abstract ConfCommand create(String value);
}
Now use the this factory as following:
Properties props = new Properties();
props.load(yourInuptStream);
for (Entry<Object, Object> e : props.entrySet()) {
CommmandFactory.valueOf((String)e.getKey()).create((String)e.getValue()).execute();
}
Upvotes: 1
Reputation: 201437
There are several patterns you might use, I might use an Interpreter pattern,
or a Command pattern
or a Strategy pattern
Upvotes: 1
Reputation: 20063
This is the perfect time to use the strategy pattern, you might want to follow the answer from this code but you'd execute a specific strategy based on the boolean
This is an excellent write up example from the guys at IntelliJ entitled
Replace conditional logic with strategy pattern
Upvotes: 1