策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口。设计一个抽象类,提供辅助函数。
//抽象策略类接口
public interface CarFunction
{
void run();
}
//定义一个策略实现类的父类
public class Car implements CarFunction
{
protected String name;
protected String color;
public Car(String name,String color)
{
this.name = name;
this.color = color;
}
@override
public void run()
{
System.out.println(color +"的"+name+"在行驶");
}
}
//具体的策略实现类
public class SamllCar extends Car
{
public SmallCar(String name ,String color)
{
super(name,color);
}
public void run()
{
System.out.println(color +"的"+name+"在高速行驶");
}
}
public class BusCar extends Car
{
public SmallCar(String name ,String color)
{
super(name,color);
}
public void run()
{
System.out.println(color +"的"+name+"在缓慢行驶");
}
}
//应用场景类
public class Person
{
private String name;
private String age;
public Person(String name ,String age)
{
this.name = name;
this.age = age;
}
public void driver(Car car)
{
System.out.println(name +" "+age+"岁,开着");
car.run();
}
}
//测试类
public class Test
{
public static void main(String[] args)
{
Car smallCar = new SmallCar("路虎","白色");
Car busCar = new BusCar("公交车","黄色");
Person people = new Person("小月月","23");
people.driver(smallCar);
people.driver(busCar);
}
}