修改if-else到策略模式 [英] Modifying if-else to strategy pattern

查看:303
本文介绍了修改if-else到策略模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中有以下if-else分支。

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 ?

推荐答案

以下是使用工厂的策略模式示例:

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)));
    }
}

这篇关于修改if-else到策略模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆