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

    策略模式的定义:

    策略模式其实特别好理解,俗话说得好,条条大路通罗马,做的都是一件事,实现的方式却可以千万种,在这种情况下,如何使得每个人都可以根据自己的喜好来选择具体的方式,在调用时可以根据不同方式的变化而互不影响的变化。

    策略模式的实现:

    1.首先定义一个策略接口。

    2.根据不同的方式具体的实现这个策略接口。

    3.在使用策略对象的类中,定义一个该策略接口的引用,通过构造方法完成赋值。

    策略模式的应用:

    1.定义一个旅行接口
    public
    interface Travel { public void transportation(); }
    2.三个不同的实现方式,分别为开车、乘火车、乘飞机旅行
    class Car implements Travel { public void transportation() { System.out.println("自己开车去欧洲旅行!"); } } class Train implements Travel { public void transportation() { System.out.println("乘火车去欧洲旅行!"); } } class Plane implements Travel { public void transportation() { System.out.println("乘飞机去欧洲旅行!"); } }
    3.定义一个对外调用的策略类,通过构造方法引入旅行接口
    public class Strategy { private Travel travel; public Strategy(Travel travel) { this.travel = travel; } public void transportation() { travel.transportation(); } }
    4.测试不同的旅行方式
    public class StrategyTest { public static void main(String[] args) { Strategy strategy = new Strategy(new Car()); strategy.transportation(); Strategy strategy1 = new Strategy(new Train()); strategy1.transportation(); Strategy strategy2 = new Strategy(new Plane()); strategy2.transportation(); } }
  • 相关阅读:
    机器学习框架之sklearn简介
    ubuntu 16.04下使用 python pip的安装问题。
    ubuntu 16.04 搭建git小型服务器
    使用config 来管理ssh的会话
    【linux】su、sudo、sudo su、sudo -i的用法和区别
    【python】确保文件写入结束
    【python】描述符descriptor
    【python】类(资料+疑惑)
    【pymongo】mongodb cursor id not valid error
    【python】继承关系和isinstance
  • 原文地址:https://www.cnblogs.com/zengxiaoliang/p/8074571.html
Copyright © 2011-2022 走看看