和大家分享一下自己的理解,有什么不对的地方,请指出
package com.shejimoshi.celuomoshi; /** * @author luoshuaiqian * @Title: Car * @Description: TODO * @date 2019/4/24 11:47 */ public class Car { /** * @Description:车辆启动 * @return: void * @auther: luoshuaiqian * @date: 2019/4/24 11:48 */ public void start() { System.out.println("car start"); } }
package com.shejimoshi.celuomoshi; /** * @author luoshuaiqian * @Title: Sedan * @Description: 轿车 * @date 2019/4/24 11:50 */ public class Sedan extends Car { //重写父类方法 public void start() { System.out.println("sedan start"); } }
package com.shejimoshi.celuomoshi; /** * @author luoshuaiqian * @Title: Trucks * @Description: 货车 * @date 2019/4/24 11:54 */ public class Trucks extends Car { //重写父类方法 public void start() { System.out.println("trucks start"); } }
package com.shejimoshi.celuomoshi; /** * @author luoshuaiqian * @Title: Test * @Description: TODO * @date 2019/4/24 11:55 */ public class Test { public static void main(String[] args) { testCar(new Sedan()); testCar(new Trucks()); } public static void testCar(Car car) { car.start(); } }
Sedan Trucks我们可以看做策略类,根据传入的不同策略,出现不同的结果。
但是再这样有很大的局限性,我们想使用testCar方法,就必须继承Car类,java只支持单继承,对于一些已经继承过的类就无法满足了。
我们可以把Car更换为接口
package com.shejimoshi.celuomoshi; /** * @author luoshuaiqian * @Title: Car * @Description: TODO * @date 2019/4/24 11:47 */ public interface Car { /** * @Description:车辆启动 * @return: void * @auther: luoshuaiqian * @date: 2019/4/24 11:48 */ void start(); }
package com.shejimoshi.celuomoshi; /** * @author luoshuaiqian * @Title: Sedan * @Description: 轿车 * @date 2019/4/24 11:50 */ public class Sedan implements Car { public void start() { System.out.println("sedan start"); } }
package com.shejimoshi.celuomoshi; /** * @author luoshuaiqian * @Title: Trucks * @Description: 货车 * @date 2019/4/24 11:54 */ public class Trucks implements Car { public void start() { System.out.println("trucks start"); } }
package com.shejimoshi.celuomoshi; /** * @author luoshuaiqian * @Title: Test * @Description: TODO * @date 2019/4/24 11:55 */ public class Test { public static void main(String[] args) { testCar(new Sedan()); testCar(new Trucks()); } public static void testCar(Car car) { car.start(); } }
这样我们就可以通过实现Car接口,来调用testCar方法。我感觉策略模式和多态差不多,第一种方法就是java多态的体现。策略模式用起来还是挺方便的,缺点就是会有很多策略类。