策略模式

定义一系列算法,将每一个算法封装起来,并让他们可以相互替换。

 

1、定义一个抽象策略类

/**
 * 定义一个购买球的策略类
 * @author Tim
 *
 */
public interface Ball {

    public double price(double price);
}
View Code

 

2、定义二种具体的策略类

/**
 * 足球的购买价钱
 * @author Tim
 *
 */
public class FootBall implements Ball{

    public double price(double price) {
        return price * 0.9;
    }

}
View Code
/**
 * 篮球类
 * @author Tim
 *
 */
public class BasketBall implements Ball{

    public double price(double price) {
        return price * 0.6;
    }

}
View Code

 

3、定义环境类(集成算法的类),采用组合的方式

/**
 * 定义环境类
 * @author Tim
 *
 */
public class Strategy {

    private Ball ball;

    public Strategy(Ball ball) {
        this.ball = ball;
    }
    
    public double priceBall(double price) {
        return this.ball.price(price);
    }
    
}
View Code

 

4、测试类

public class StrategyMain {

    public static void main(String[] args) {
        
        Ball ball = new FootBall();
        Strategy strategy = new Strategy(ball);
        System.err.println(strategy.priceBall(18));
    }
}
View Code

 

posted @ 2018-05-07 17:30  秋水秋色  阅读(98)  评论(0编辑  收藏  举报