JAVA设计模式

Java设计模式之一策略模式

2019-06-26  本文已影响0人  095b62ead3cd

策略模式

策略模式属于对象的一种行为模式。它主要表现在对象通过一个抽象的策略角色调用由多个具有共同接口的独立类或抽象类时达到相关算法随意相互替换的结果。它针对的是一组具有相同接口的不同算法。

这个模式涉及到三个角色:

环境角色:引用者对象
抽象策略角色:通常由一个独立类或者抽象类实现
具体策略:包装相关的算法或者行为

示例:

领导要求小明明天过来公司加班,小明可以选择打车来公司,可以选择骑车来公司,也可以选择坐公交来公司,也可以选择坐地铁来公司等等方式,那么这里面小明过来公司加班这件事就可以用策略模式来表达。
小明-->环境角色,谁
利用交通工具-->抽象策略角色,来的结果
乘坐各种交通工具-->具体策略,来的具体过程

这里我们就可以定义一个接口类Port

public interface Port{
     public void goToOffice();
}

再定义几个这个接口的实现类,用于表示来的过程

public class ByCar implements Port{
      public void goToOffice(){
          System.out.println("打车");
      }
}
public class ByBike implements Port{
      public void goToOffice(){
          System.out.println("骑车");
      }
}
public class ByBus implements Port{
      public void goToOffice(){
          System.out.println("坐公交");
      }
}
public class ByMetro implements Port{
      public void goToOffice(){
          System.out.println("坐地铁");
      }
}

接着是抽象结果类的定义

public class GoOffice {
     private Port port;
      public GoOffice(Port port){
        this.port = port;
      }
     public void goToOffice(){
          this.port.goToOffice();
      }
}

最后我们看具体的执行者,小明

public class XiaoMing {
      public static void main(String[] args){
            GoOffice goOffice;
            goOffice = new GoOffice(new ByCar());//此处想用什么方式去就调用什么方式
            goOffice.goToOffice();
       }
}
上一篇 下一篇

猜你喜欢

热点阅读