标签:close one ble adb b16 style isp nbsp 替换
定义一系列算法,将每一个算法封装起来,并让他们可以相互替换。
1、定义一个抽象策略类
/** * 定义一个购买球的策略类 * @author Tim * */ public interface Ball { public double price(double price); }
2、定义二种具体的策略类
/** * 足球的购买价钱 * @author Tim * */ public class FootBall implements Ball{ public double price(double price) { return price * 0.9; } }
/** * 篮球类 * @author Tim * */ public class BasketBall implements Ball{ public double price(double price) { return price * 0.6; } }
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); } }
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)); } }
标签:close one ble adb b16 style isp nbsp 替换
原文地址:https://www.cnblogs.com/codechange/p/9003937.html