类型:行为模式
定义一组算法,将每个算法都封装起来,并且使它们之间可以互换。策略模式使这些算法在客户端调用它们的时候能够互不影响地变化。interface tyre_interface { // tyre 轮胎 public void print_tyre_line();// 显示出轮胎的痕迹}//长痕迹轮胎类 class tyre_long_implement implements tyre_interface { public void print_tyre_line() { System.out.println("在路面上显示一个长轮胎痕迹"); }}//短痕迹轮胎类 class tyre_short_implement implements tyre_interface { public void print_tyre_line() { System.out.println("在路面上显示一个短轮胎痕迹"); }}class Car2 { 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(); }}public class 策略模式 { 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(); Car2 car = new Car2(); car.setDeath_year(8); car.setMake_address("北京朝阳区"); car.setSpeed(200); car.setTyre_interface_ref(tyre_long_implement); car.start(); }}