美文网首页
设计模式-strategy

设计模式-strategy

作者: Wu杰语 | 来源:发表于2020-12-13 17:19 被阅读0次

策略模式是一种封装,将不同的算法用策略模式封装起来。在这个模式中,用到了工厂模式。

例子

interface Algo {
  public void calc();
}

class A impletement Algo {
  public void calc() {}
}
class B impletement Algo {
  public void calc() {}
}
class C impletement Algo {
  public void calc() {}
}

class Factory {
  static Algo getAlgo(String name) {
    if ("A".equal(name)) {
      return new A();
    } else if ("B".equal(name)) {  
      return new B();
    } else if ("C".equal(name)) {
      return new C();
    }
    return null;
}

class Demo {
  public static void main(String[] args) {
    Algo algo = Factory.getAlgo("A");
    algo.clac();
  }
}

从上面可以看到,通过使用策略模式,使得用户代码与具体算法解耦,具体算法可以根据情况扩展。

小结

策略模式是一种解耦代码的方式,通过策略模式,实际上将算法的if else选择集中封装到Factory中,扩展的变化也在Factory中了。

相关文章

网友评论

      本文标题:设计模式-strategy

      本文链接:https://www.haomeiwen.com/subject/kjrpgktx.html