相关疑难解决方法(0)

使用战略模式的好处在哪里?

在维基百科上看过这个解释,特别是C++示例,并且没有认识到只定义3个类,创建实例和调用它们之间的区别,以及那个例子.我看到的只是将其他两个类放入流程中,无法看到哪里会有好处.现在我肯定我错过了一些明显的东西(树木) - 有人可以用一个明确的现实世界的例子来解释它吗?


到目前为止,我可以从答案中得到什么,在我看来,这只是一种更为复杂的方式:

have an abstract class: MoveAlong with a virtual method: DoIt()
have class Car inherit from MoveAlong, 
     implementing DoIt() { ..start-car-and-drive..}
have class HorseCart inherit from MoveAlong, 
     implementing DoIt() { ..hit-horse..}
have class Bicycle inherit from MoveAlong, 
     implementing DoIt() { ..pedal..}
now I can call any function taking MoveAlong as parm 
passing any of the three classes and call DoIt
Isn't this what Strategy intents? (just simpler?)
Run Code Online (Sandbox Code Playgroud)

[编辑 - 更新]我在上面引用的函数被替换为另一个类,其中MoveAlong属于属性,根据需要根据在这个新类中实现的算法设置.(与接受的答案中的内容类似.)


[编辑 - 更新] …

design-patterns strategy-pattern

12
推荐指数
3
解决办法
9820
查看次数

这种"呼叫倒置"模式是否有名称?

我刚回答了另一个问题(选择基于类中字段的方法),我想知道模式是否有名称.

调用action.applyX(a),X取决于某些属性a(例如type在示例中),因此您调用a.apply(action)并让a(或Type)调用适当的属性applyX.

那有名字吗?

public enum Type {
    INTEGER {
        @Override
        public void apply(Action action, A a) {
            action.applyInteger(a);
        }
    },
    STRING {
        @Override
        public void apply(Action action, A a) {
            action.applyString(a);
        }
    };
    public abstract void apply(Action action, A a);
}

public interface Action {
    public void applyInteger(A a);
    public void applyString(A a);
}

public class A {
    private Type type;
    ... …
Run Code Online (Sandbox Code Playgroud)

java design-patterns

1
推荐指数
1
解决办法
511
查看次数

标签 统计

design-patterns ×2

java ×1

strategy-pattern ×1