zoukankan      html  css  js  c++  java
  • 策略模式

    策略模式

    1 public interface Strategy {
    2 
    3     void algorithmInterface();
    4 }
     1 public class Context {
     2 
     3     private Strategy strategy;
     4     
     5     public Context(Strategy strategy){
     6         this.strategy = strategy;
     7     }
     8     
     9     public void uStrategy(){
    10         this.strategy.algorithmInterface();
    11     }
    12 }
     1 public class ConcreteStrategyA implements Strategy {
     2 
     3     @Override
     4     public void algorithmInterface() {
     5         // TODO Auto-generated method stub
     6 
     7         System.out.println("A Strategy works");
     8     }
     9 
    10 }
     1 public class ConcreteStrategyB implements Strategy {
     2 
     3     @Override
     4     public void algorithmInterface() {
     5         // TODO Auto-generated method stub
     6 
     7         System.out.println("B Strategy works");
     8     }
     9 
    10 }
     1 public class ConcreteStrategyC implements Strategy {
     2 
     3     @Override
     4     public void algorithmInterface() {
     5         // TODO Auto-generated method stub
     6 
     7         System.out.println("C Strategy works");
     8     }
     9 
    10 }

    设计基类Duck,子类MallarDuck,RedheadDuck,RubberDuck,duck can swim(),fly(),quack().

    方法一:

    很明显,rubberduck也会飞了,如果以后在增加鸭子类别,则需要重写fly,灵活性低,复用不当。

    方法二:把变化的部分分离出来,即将fly放在接口中,会飞的鸭子继承这个借口,如图

    如此一来破坏了复用性,每一种鸭子都需要实现fly(),不如方法一中直接继承的复用性强。

    方法三:

    面向接口

    扩展了fly与quack的方式,使用接口的引用完成了变化的封装

  • 相关阅读:
    spring注解开发AnnotationConfigApplicationContext的使用
    java.rmi.server.ExportException: Port already in use: 1099; nested exception is
    mac 入门操作
    postgreSql 常用查询总结
    Tomcat专题
    Java反射
    notepad++ jstool 插件安装
    Java集合
    Java 集合并交补
    C++回调函数(callback)的使用
  • 原文地址:https://www.cnblogs.com/anqiang1995/p/7623372.html
Copyright © 2011-2022 走看看