blue-sky
blue-sky

Reputation: 53806

Design pattern for handling app configuration

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

Answers (4)

wlk
wlk

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

AlexR
AlexR

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

Elliott Frisch
Elliott Frisch

Reputation: 201437

There are several patterns you might use, I might use an Interpreter pattern,

Interpreter Pattern

or a Command pattern

Command Pattern

or a Strategy pattern

Stategy Pattern

Upvotes: 1

David
David

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

Related Questions