将 if-else 修改为策略模式

发布于 2024-11-17 23:10:32 字数 214 浏览 2 评论 0原文

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

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

如何将此代码修改为策略模式?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

智商已欠费 2024-11-24 23:10:32

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

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

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)));
    }
}
我不吻晚风 2024-11-24 23:10:32

您必须从面向对象编程的角度进行思考。使用多态性。
对于策略模式来说,
定义一个接口并为实现该接口的类提供不同的实现。选择上下文并多态地决定类。
http://en.wikipedia.org/wiki/Strategy_pattern

但是对于您的 if-否则正确的模式对应于“工厂模式”。
http://en.wikipedia.org/wiki/Factory_method_pattern

You have to think in terms of object-oriented programming. Use Polymorphism.
For strategy pattern,
Define an interface and provide different implementations to classes which implements the interface. Choose context and decide the class ploymorphically.
http://en.wikipedia.org/wiki/Strategy_pattern

However for your if-else the correct pattern corresponds to 'Factory Pattern'.
http://en.wikipedia.org/wiki/Factory_method_pattern

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文