• <二>读<<大话设计模式>>之策略模式


           又和大家见面了。可以坚持写出第二篇文章真不错,好好加油。

           <<大话设计模式>>解说策略模式是以商场收银软件程序开头的,那么问题来了。哪家商场收银软件强,开玩笑了。

    读过上篇文章《《简单工厂模式》》的知道,它有两个缺点:1、client依赖两个类。耦合性高;2、假设算法过多则须要写非常多类。解决上面问题的就是策略模式了。

    策略模式:它定义了算法家族。分别封装起来。让它们之间能够互相替换,此模式让算法的变化,不会影响到使用算法的客户。

    商场收银软件:单位价格*打折算法=售价。对于这种软件来说,须要常常变化的是打折算法。其有用简单工厂模式全然能够的。直接添加打折算法,然后工厂生产实例对象就能够了。

           可是这个模式知识解决对象创建问题,并且因为工厂本身包含了全部收费方式,商场是可能常常更改打折算法的,每次维护或扩展收费方式都要修改这个工厂。这样是很麻烦也不遵循易扩展、易复用原则。事实上分析一下该软件的变化点就是打折算法,我们仅仅要将这个变化点封装起来就行了,而策略模式可以做到这一点。

    好了。上代码了。依据样例学习进步快

    1、策略类,定义了全部算法实现的公共方法接口

    /*

     * 策略类

     */

    publicabstractclass Strategy {

     

        /*

         * 定义全部算法的公共接口

         */

        publicabstractvoid algorithmlnterface();

    }

    2、维护一个对Strategy类的引用。想调用那个类就调用那个类

    /*

     * 维护对strategy对象的引用

     */

    publicclass Context {

     

        Strategystrategy;

        public Context(Strategy strategy){

           this.strategy = strategy;

        }

       

        publicvoid contextInterface(){

           strategy.algorithmlnterface();

        }

    }

    3、算法a

    publicclass ConcreteStrategyAextends Strategy {

     

        @Override

        publicvoid algorithmlnterface() {

           //TODO Auto-generated method stub

     

           System.out.println("this is algorithm a ;");

        }

     

    }

    4、算法b

    publicclass ConcreteStrategyBextends Strategy {

     

        @Override

        publicvoid algorithmlnterface() {

           //TODO Auto-generated method stub

     

           System.out.println("this is algorithm b ;");

        }

     

    }

    5、client调用

    publicclass StrategyClient {

     

        /**

         * @param args

         */

        publicstaticvoid main(String[] args) {

           //TODO Auto-generated method stub

     

           /*

            * 对照与工厂模式,该client只依赖于Context类,解耦更加彻底

            * 添加一个算法只须要添加一个算法类就可以

            */

           Contextcontext = new Context(new ConcreteStrategyA());

           context.contextInterface();

           //看到了吧。想要B算法就直接实例一下就能够调用它的方法了

           Contextcontext2 = new Context(new ConcreteStrategyB());

           context2.contextInterface();

        }

     

    }

    总结:策略模式是一种定义一系列算法的方法,从概念上来看,全部这些算法完毕的都是同样的工作,仅仅是实现不同。它能够以同样的方式调用全部的算法,降低了各种算法类与使用算法类之间的耦合。

    附上代码地址:http://download.csdn.net/detail/jzhf2012/8084405

  • 相关阅读:
    redis配置文件 redis.conf
    CentOS安装 NodeJS 和 NPM
    Docker中运行redis报错误: Failed opening the RDB file root (in server root dir /etc/cron.d) for saving: Permission denied
    AllowControlAllowOrigin:谷歌跨域扩展插件下载
    uniapp 判断客户端环境是安卓还是ios
    Windows环境下查看某个端口被哪个应用程序占用并停止程序
    Oracle数据库快速入门
    Linux 使用vim命令编辑文件内容
    解决VMware Workstation客户机与宿主机无法复制文件和共享剪切板的问题
    Spring 中的事件机制 ApplicationEventPublisher
  • 原文地址:https://www.cnblogs.com/llguanli/p/6737057.html
Copyright © 2020-2023  润新知