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

    结构图:

    实现:

    1 abstract public class Strategy {
    2     public void algrithmInterface()
    3     {    
    4     }
    5 }
     1 public class StrategyA extends Strategy{
     2 
     3     @Override
     4     public void algrithmInterface() {
     5         super.algrithmInterface();
     6         System.out.println("算法A的实现");
     7     }
     8     
     9 
    10 }
     1 public class StrategyB extends Strategy{
     2 
     3     @Override
     4     public void algrithmInterface() {
     5         super.algrithmInterface();
     6         System.out.println("算法B的实现");
     7     }
     8     
     9 
    10 }
     1 public class Context {
     2 
     3     private Strategy strategy;
     4 
     5     public Context(Strategy strategy) {
     6         super();
     7         this.strategy = strategy;
     8     }
     9     
    10     public void contextInterface()
    11     {
    12         strategy.algrithmInterface();
    13     }
    14     
    15     public void setStrategy(Strategy s)
    16     {
    17         this.strategy = s;
    18     }
    19 }
     1 public class Client {
     2     public static void main(String[] args)
     3     {
     4         Context context = new Context(new StrategyA());
     5         context.contextInterface();
     6         
     7         context.setStrategy(new StrategyB());
     8         context.contextInterface();
     9     }
    10 }

    应用常用:
    该模式封装了一系列算法,让它们而已相互替换,而不会影响到客户端的变化。

  • 相关阅读:
    密码框组件
    文本框组件
    列表框组件
    复选框组件
    单选按钮组件
    nginx for windows
    Mesa 3D
    下载服务器文件到本地
    消息服务
    Redis查看已注册的提供者消费者信息
  • 原文地址:https://www.cnblogs.com/gatsbydhn/p/4998698.html
Copyright © 2011-2022 走看看