Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying if-else to strategy pattern

I have the following if-else branch in java.

    if (str.equals("a")) { A;}
else if (str.equals("b")) { B;}
else if (str.equals("c")) { C;}
else if (str.length == 5) { D;}
else { E;}

how to modify this code into strategy pattern ?

like image 368
sam Avatar asked Jun 30 '11 04:06

sam


People also ask

How do you implement a Strategy pattern?

In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object.

What is the solution to the strategy design pattern?

Solution with strategy design pattern To implement the solution, let's design one participant one at a time. ISocialMediaStrategy – The interface which abstract the operation. SocialMediaContext – The context which determines the implementation. Implementations – Various implementations of ISocialMediaStrategy .

What is the difference between pattern and strategies?

State pattern helps a class to exhibit different behaviors in a different state. Strategy Pattern encapsulates a set of related algorithms and allows the client to use interchangeable behaviors through composition and delegation at runtime.

Which design pattern lets you alter an object's behavior at runtime by associating it with different sub objects to perform several tasks?

The Strategy pattern lets you indirectly alter the object's behavior at runtime by associating it with different sub-objects which can perform specific sub-tasks in different ways.


1 Answers

Here an example of a strategy pattern using a factory:

public interface Strategy {
    public Object[] execute(Object[] args);
}

public class StrategyFactory {

    public enum Name {
        REVERSE, STRINGIFY, DUPLICATE;
    }

    private StrategyFactory() {
        // never instantiate; only use static factory methods
    }

    public static Strategy getStrategyReverse() {
        return new Strategy() {
            public Object[] execute(Object[] args) {
                Object[] reversed = new Object[args.length];
                for (int i = 0; i < args.length; i++) {
                    reversed[i] = args[args.length - i - 1];
                }
                return reversed;
            }
        };
    }

    public static Strategy getStrategyStringify() {
        return new Strategy() {
            public Object[] execute(Object[] args) {
                String[] stringified = new String[args.length];
                for (int i = 0; i < args.length; i++) {
                    stringified[i] = String.valueOf(args[i]);
                }
                return stringified;
            }
        };
    }

    public static Strategy getStrategyDuplicate() {
        return new Strategy() {
            public Object[] execute(Object[] args) {
                Object[] duplicated = new Object[2 * args.length];
                for (int i = 0; i < args.length; i++) {
                    duplicated[i * 2] = args[i];
                    duplicated[i * 2 + 1] = args[i];
                }
                return duplicated;
            }
        };
    }

    public static Strategy getStrategy(String name) {
        return getStrategy(Name.valueOf(name));
    }

    public static Strategy getStrategy(Name name) {
        switch (name) {
            case REVERSE:
                return getStrategyReverse();
            case STRINGIFY:
                return getStrategyStringify();
            case DUPLICATE:
                return getStrategyDuplicate();
            default:
                throw new IllegalStateException("No strategy known with name " + name);
        }
    }
}

public class Main {
    public static void main(String[] args) {

        Strategy strategy = StrategyFactory.getStrategy("DUPLICATE");
        System.out.println(Arrays.toString(strategy.execute(args)));
    }
}
like image 88
Adriaan Koster Avatar answered Oct 23 '22 15:10

Adriaan Koster