码迷,mamicode.com
首页 > 编程语言 > 详细

java设计模式(六)策略模式

时间:2017-07-19 23:28:07      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:foo   logs   out   ring   定义   nts   引用   ace   java   

  策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们可以相互替换,让算法独立于使用它的客户而独立变化,具体应用场景如第三方支付对接不同银行的算法。

  要点:1)抽象策略角色

        2)具体策略角色:包装相关算法和行为

     3)环境角色:持有一个策略类的引用,最终给客户端调用

1、抽象策略接口

public interface SwimmingStratege {
    public void swimming();
}

2、具体策略角色SwimmingWithFoot 

public class SwimmingWithFoot implements SwimmingStratege {
    public void swimming() {
        System.out.println("我借助脚滑动在水中游走");
    }
}

3、具体策略角色SwimmingWithWind 

public class SwimmingWithWind implements SwimmingStratege {
    public void swimming() {
        System.out.println("我借助风在水中游走");
    }
}

4、环境角色Duck 抽象类

public abstract class Duck {

    public void quack() {
        System.out.println("嘎嘎嘎");
    }

    public abstract void display();

    private SwimmingStratege swimmingStratege;

    public void setSwimmingStratege(SwimmingStratege swimmingStratege) {
        this.swimmingStratege = swimmingStratege;
    }

    public void swimming() {
        swimmingStratege.swimming();
    }
}

5、环境角色RealDuck

public class RealDuck extends Duck {

    public RealDuck() {
        super();
        super.setSwimmingStratege(new SwimmingWithFoot());
    }

    @Override
    public void quack() {
        super.quack();
    }

    public void display() {
        System.out.println("我是真的鸭子");
    }
}

6、环境角色

public class YellowDuck extends Duck {

    public YellowDuck() {
        super();
        super.setSwimmingStratege(new SwimmingWithWind());
    }

    @Override
    public void quack() {
        super.quack();
    }

    public void display() {
        System.out.println("我是大黄鸭");
    }

}

7、测试

public class Model {

    public static void main(String[] args) {
        Duck duck = new RealDuck();
//        Duck duck = new YellowDuck();
        duck.display();
        duck.quack();
        duck.swimming();
    }

}

 

java设计模式(六)策略模式

标签:foo   logs   out   ring   定义   nts   引用   ace   java   

原文地址:http://www.cnblogs.com/sunjf/p/stratege.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!