首页 > 代码库 > java设计模式(六)策略模式

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设计模式(六)策略模式