• 设计模式学习06:策略模式和简单工厂模式


    设计模式学习06:策略模式和简单工厂模式

    策略模式

     定义

      定义一组算法,将每个算法都封装起来,并且使它们之间可以互换。

      策略模式(Strategy Pattern) 也叫 政策模式(Policy Pattern)。指的是对象具备某个行为,但是在不同的场景中,该行为有不同的实现算法。比如一个人的交税比率与他的工资有关,不同的工资水平对应不同的税率。

      策略模式 使用的就是面向对象的继承和多态机制,从而实现同一行为在不同场景下具备不同实现

    主要解决

      在有多种算法相似的情况下,使用 if...else 或 switch...case 所带来的复杂性和臃肿性。

    优点

      算法多样性,且具备自由切换功能;

      有效避免多重条件判断,增强了封装性,简化了操作,降低出错概率;

      扩展性良好,策略类遵顼 里氏替换原则,可以很方便地进行策略扩展;

    缺点

      策略类数量增多,且所有策略类都必须对外暴露,以便客户端能进行选择;

    使用场景

      针对同一类型问题,有多种处理方式,每一种都能独立解决问题;

      算法需要自由切换的场景;

      需要屏蔽算法规则的场景;

    三种角色

      上下文角色(Context):用来操作策略的上下文环境,屏蔽高层模块(客户端)对策略,算法的直接访问,封装可能存在的变化;

      抽象策略角色(Strategy):规定策略或算法的行为;

      具体策略角色(ConcreteStrategy):具体的策略或算法实现;

    通用代码

    class Client {
        public static void main(String[] args) {
            //选择一个具体策略
            IStrategy strategy = new ConcreteStrategyA();
            //来一个上下文环境
            Context context = new Context(strategy);
            //客户端直接让上下文环境执行算法
            context.algorithm();
        }
    
        //抽象策略类 Strategy
        interface IStrategy {
            void algorithm();
        }
    
        //具体策略类 ConcreteStrategy
        static class ConcreteStrategyA implements IStrategy {
    
            @Override
            public void algorithm() {
                System.out.println("Strategy A");
            }
        }
    
        //具体策略类 ConcreteStrategy
        static class ConcreteStrategyB implements IStrategy {
    
            @Override
            public void algorithm() {
                System.out.println("Strategy B");
            }
        }
    
        //上下文环境
        static class Context {
            private IStrategy mStrategy;
    
            public Context(IStrategy strategy) {
                this.mStrategy = strategy;
            }
    
            public void algorithm() {
                this.mStrategy.algorithm();
            }
        }
    }

     具体案例

      案例说明:司机开车,可以选择的交通工具有自行车、汽车、火车

       上下文角色(Context)

    //接口-交通工具
    public interface Vehicle {
    
        void showWheelAmount();
    
        void run();
    }

       抽象策略角色(Strategy)

    //具体类-自行车
    public class Bike implements  Vehicle {
    
    
        @Override
        public void showWheelAmount() {
            System.out.println("bike has two wheels");
        }
    
        @Override
        public void run() {
                System.out.println("bike is running!");
        }
    }
    //具体类-汽车
    public class Car implements Vehicle {
    
        @Override
        public void showWheelAmount() {
            System.out.println("car has four wheels");
        }
    
        @Override
        public void run() {
            System.out.println("car is running!");
        }
    }
    //具体类-火车
    public class Train implements Vehicle {
        @Override
        public void showWheelAmount() {
            System.out.println("train has many wheels");
        }
    
        @Override
        public void run() {
            System.out.println("train is running!");
        }
    }

       具体策略角色(ConcreteStrategy)

    //司机
    public class Driver {
    
        public static void main(String[] args) {
            Vehicle bike = new Bike();
            bike.showWheelAmount();//bike has two wheels
            bike.run();// bike is running!
    
            Vehicle car = new Car();
            car.showWheelAmount();//car has four wheels
            car.run(); //car is running!
        }
    }

    简单工厂模式

    主要角色

      工厂:负责实现创建所有实例的内部逻辑,并提供一个外界调用的方法,创建所需的产品对象。

      抽象产品:负责描述产品的公共接口

      具体产品:描述生产的具体产品。

    具体案例

      案例说明:工厂生产交通工具,有自行车、汽车、火车

      抽象产品:Vehicle .java,和上一个案例通用

      具体产品:自行车、汽车、火车,和上一个案例通用

      工厂

    //具体工厂
    public class VehicleFactory {
    
        public static Map<String,Vehicle> vehiclesMap = new HashMap<>();
    
        static{
            vehiclesMap.put("bike", new Bike());
            vehiclesMap.put("car", new Car());
            vehiclesMap.put("train", new Train());
        }
    
        //根据类型生产交通工具
        public static Vehicle createNewVehicle(String  type){
            try {
                return vehiclesMap.get(type);
            } catch (Exception e) {
                throw  new RuntimeException();
            }
        }
    }

       生产交通工具

    //生产交通工具
    public class VehicleCreate {
    
        public static void main(String[] args) {
            //生产
            String vehicleType = "car";
            Vehicle newVehicle = VehicleFactory.createNewVehicle(vehicleType);
            //试用
            newVehicle.showWheelAmount();//car has four wheels
            newVehicle.run();//car is running!
        }
    }
    
            
  • 相关阅读:
    4.net基础之委托事件
    2.net基础之反射
    绕过百度网盘速度限制直接下载百度网盘文件
    1.net基础之泛型
    网页图片按需加载
    小米官网图片轮播
    html+css3实现网页时钟
    接口自动化测试方案详解
    接口测试用例设计实践总结
    Mysql 高可用(MHA)-读写分离(Atlas)
  • 原文地址:https://www.cnblogs.com/wobuchifanqie/p/11953662.html
Copyright © 2020-2023  润新知