• Java 策略模式


    策略模式

    策略模式属于对象的行为模式。其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。

    这个模式涉及到三个角色
    • 环境角色

      • 引用者

    • 抽象策略角色

      • 通常由一个接口或者抽象类实现

    • 具体策略

      • 包装相关的算法或者行为

    例子

    我们模拟一下 两位学生在课间中的行为

    Student 类 (引用者)

    public class Student {
        
        // 具体策略对象
        private Action action;
    ​
        public Student( Action action){
            this.action = action;
        }
    ​
        // 学生的行为
        public void studentAction(){
            action.action();
        }
        
    }

    Action 接口 (抽象策略角色)

    public interface Action {
        //学生的动作
        void action();
    }
    ​

    SleepAction类(具体策略)

    public class SleepAction implements Action {
        @Override
        public void action() {
            System.out.println("正在睡觉......");
        }
    }
    ​

    PlayAction类 (具体策略)

    public class PlayAction implements Action {
        @Override
        public void action() {
            System.out.println("正在玩耍.......");
        }
    }

    Test类(测试类)

    public class Test {
        public static void main(String[] args) {
            // 睡觉的行为
            Action sleep = new SleepAction();
            // 玩的行为
            Action play = new PlayAction();
            
            //小明
            Student xiaoming = new Student(sleep);
            xiaoming.studentAction();
            //小明明
            Student mingming = new Student(play);
            mingming.studentAction();
        }
    }

    结果

    正在睡觉......
    正在玩耍.......
  • 相关阅读:
    swagger生成接口文档
    二分查找通用模板
    go-json技巧
    【Go】获取用户真实的ip地址
    数据库储存时间类型
    密码加密:md5/sha1 +盐值
    参数里时间格式的转换
    不好定位的元素定位
    vim编辑器
    ps -ef | grep php kill -9
  • 原文地址:https://www.cnblogs.com/oukele/p/10678661.html
Copyright © 2020-2023  润新知