设计模式笔记之----策略模式

来源:互联网 发布:360新一代安全网络导航 编辑:程序博客网 时间:2024/05/18 20:11

策略模式属于 行为型模式,属于比较简单的一个模式了,顾名思义,是把策略封装起来的模式,然后使用的时候传入策略对象,就会执行相应的方法了。例子就是,假如我是动物饲养员,然后每一种动物都有一个策略去喂养,于是我们把喂养的策略封装成N个喂养说明的小本子,当去喂一个动物的时候就拿对应的说明去喂养。

代码:
首先定义一个策略的接口,接下来的几个策略都实现这个接口:

package StrategyPattern;public interface StrategyInf {    void diIt();}

然后实现接口:

package StrategyPattern;public class Strategy00 implements StrategyInf{    @Override    public void diIt() {        // TODO Auto-generated method stub        System.out.println("策略1");    }}

最后定义一个调用类:

package StrategyPattern;public class MyStrategy {    private StrategyInf strategyInf;    public MyStrategy(StrategyInf strategyInf){        this.strategyInf = strategyInf;    }    public void execStrategy(){        strategyInf.diIt();    }    public static void main(String[] args){        MyStrategy myStrategy = new MyStrategy(new Strategy02());        myStrategy.execStrategy();    }}

所以执行的时候只需要创建一个调用类,然后传入响应的策略算法:

MyStrategy myStrategy = new MyStrategy(new Strategy02());        myStrategy.execStrategy();
0 0
原创粉丝点击