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 }

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

  • 相关阅读:
    Hello Springboot
    Spring AOP
    代理模式
    Spring 面向注解开发
    Spring Bean 的配置
    IDEA 14 for Mac 提示要安装java 6的修改
    NAS DIY
    Maven Jetty SSL配置
    图书管理系统(jsp+nysql实现)
    互联网+XX项目技术架构
  • 原文地址:https://www.cnblogs.com/gatsbydhn/p/4998698.html
Copyright © 2011-2022 走看看