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

    先看一下策略模式的三个角色:

    抽象策略:仅提供一个抽象方法,环境类调用抽象策略的方法,根据实际应用情况由适合的具体策略对象去实现

    具体抽象:负责实现抽象策略定义的接口

    环境类:环境类负责引用抽象策略,并交给客户端来使用。

    简单来说就是客户端调用环境类,环境类调用抽象策略,具体的算法由不同的具体策略来实现。

    抽象策略

    public interface algorithm {
        int returnNumber(int a,int b);
    }

    具体策略1

    public class getSum implements  algorithm{
        @Override
        public int returnNumber(int a, int b) {
            return a+b;
        }
    }

    具体策略2

    public class getBigger implements algorithm {
        @Override
        public int returnNumber(int a, int b) {
            return a = a > b ? a : b;
        }
    }

    环境类

    public class Context {
        algorithm algorithm;
    
        public Context(algorithm algorithm) {
            this.algorithm = algorithm;
        }
        public int algorithm(int a,int b){
         return  algorithm.returnNumber(a,b);
        }
    }

    测试类

    public class Client {
        public static void main(String[] args) {
            Context context = new Context(new getBigger());
            System.out.println(context.algorithm(10,20));
            Context context1 = new Context(new getSum());
            System.out.println(context1.algorithm(10,20));
        }
    }

    可以看出,环境类只是一个对抽象策略类有关联作用的类而已,并提供一个方法给客户端类调用。具体的算法由具体策略类来实现。当添加新的方法的时候,不需要修改源代码,只需要添加一个新的具体策略类,环境类无需改变。

    应用场景:多个类只是具体实现不同,这时候可以使用策略模式,在运行的时候动态的选择具体要执行的行为。

    不和别人一样,不复制只真正理解
  • 相关阅读:
    点击按钮在表格的某一行下,在添加一行(HTML+JS)
    13
    12 stark组件之pop,按钮,url,页面
    11 stark组件之delete按钮、filter过滤
    解决 AttributeError: 'ForeignKey' object has no attribute 're'
    360面经
    4 django篇
    0- 26个面试经典问题回答
    如何学习??
    LeetCode
  • 原文地址:https://www.cnblogs.com/Vinlen/p/12792288.html
Copyright © 2011-2022 走看看