سؤال

I need to create a complex configuration object based on the values of params I receive.

My inputs are 2 simple variables, and a configuration object. The combination of the 2 variables, and the config object's internals will determine the configuration of the output class (which is always the same type)

Doing this with simple if-else it'd look like this:

if (a == 1 && b == 1) {
//do some testing on the input object, configure and return the output object
else if (a == 2 && b == 1) {
//do some different testing on the input, configure and return the output.
}

and on.

There are about 5 different values that a & b could hold and depending on the values of a & b, I'm going to have to test for different things within the input object.

I'm not really sure of the best way to solve this. My first thought is to have some kind of Command Pattern with a method like:

public interface Command {
  public OutputConfig execute(InputConfig config);
}

and store my potential a & b combinations in Map<Pair<A,B>, Command> for lookup.

I feel like I'm looking for some Factory / Command / Builder pattern but not sure of the best way to implement this.

Thanks in advance.

هل كانت مفيدة؟

المحلول

I think you need the Strategy Pattern. You define an interface with a method:

interface Configure{

public YourObject excecute(YourObject o);

}

You implement the interface in the variety of ways you want and you declare it as a member field. Then you instantiate the appropriate class according to the values of the variables.

If you want to save the Objects then you can use the Command Pattern as well.

Update: Ok in Software Enginneering there is usually no absolute truth.

With the Command Pattern you have already a class that does some tasks and you want to save them as Objects from a class deriving from an interface, in order to use them later etc. I do not reckon that your case requires such an approach, since you need merely diverse functionalities defined as an interface method. Strategy Pattern is therefore in your case a more elegant approach.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top