转自:
?
新建一个轮胎接口:
??? 新建2个轮胎接口的实现类:
基于一个轮胎接口来实现不同样式的轮胎样式。
??? 组装一个Car车类:
package?car_package; import?strategy_interface.tyre_interface; public?class?Car?{ ????private?String?make_address;//?制造地 ????private?int?death_year;//?报废年限 ????private?int?speed;//?速度 ????private?tyre_interface?tyre_interface_ref;//?轮胎的样式 ????public?String?getMake_address()?{ ????????return?make_address; ????} ????public?void?setMake_address(String?make_address)?{ ????????this.make_address?=?make_address; ????} ????public?int?getDeath_year()?{ ????????return?death_year; ????} ????public?void?setDeath_year(int?death_year)?{ ????????this.death_year?=?death_year; ????} ????public?int?getSpeed()?{ ????????return?speed; ????} ????public?void?setSpeed(int?speed)?{ ????????this.speed?=?speed; ????} ????public?tyre_interface?getTyre_interface_ref()?{ ????????return?tyre_interface_ref; ????} ????public?void?setTyre_interface_ref(tyre_interface?tyre_interface_ref)?{ ????????this.tyre_interface_ref?=?tyre_interface_ref; ????} ????public?void?start()?{ ????????System.out.println("车的基本信息为:"); ????????System.out.println("制造地make_address:"?+?this.getMake_address()); ????????System.out.println("报废年限death_year:"?+?this.getDeath_year()); ????????System.out.println("速度speed:"?+?this.getSpeed()); ????????System.out.println("Car?起动了!"); ????????System.out.println("Car高速行驶,遇到一个大转弯,路面显示:"); ????????this.getTyre_interface_ref().print_tyre_line(); ????} } |
??? 让车跑起来,并且具有更换轮胎样式的功能:
package?main_run; import?strategy_implement.tyre_long_implement; import?strategy_implement.tyre_short_implement; import?car_package.Car; public?class?run_main?{ ????public?static?void?main(String[]?args)?{ ????????tyre_long_implement?tyre_long_implement?=?new?tyre_long_implement(); ????????tyre_short_implement?tyre_short_implement?=?new?tyre_short_implement(); ????????Car?car?=?new?Car(); ????????car.setDeath_year(8); ????????car.setMake_address("北京朝阳区"); ????????car.setSpeed(200); ????????car.setTyre_interface_ref(tyre_long_implement); ????????car.start(); ????} } |
??? 控制台打印出:
??? 是一个长轮胎痕迹,但在程序中可以使用代码:car.setTyre_interface_ref(tyre_long_implement);来对轮胎的样式进行不同的替换,可以替换成短轮胎痕迹的汽车轮胎,这样在不更改Car类的前题下进行了不同轮胎样式的改变,轮胎和轮胎之间可以互相替换,这就是策略模式。
?
参考:
?
?
?