所谓策略模式,即创建一个根据所传递参数对象的不同具有不同行为的方法,这主要是依据多态实现的。
将基类作为参数定义某方法,而实际传入不同的子类对象,也就通过后期绑定调用了不同的方法,即采取了不同的策略。
abstract class PersonComing {
abstract void process(Person person);
}
class FriendComing extends PersonComing {
void process(Person friend) {
System.out.println("say hello to " + friend);
}
}
class ThiefComing extends PersonComing {
void process(Person thief) {
System.out.println("call 110 to arrrest " + thief);
}
}
class Person {
String name;
Person(String str) {
name = str;
}
public String toString() {
return name;
}
}
public class Test {
static void deal(PersonComing meet, Person person) {
meet.process(person);
}
public static void main(String[] args) {
Person friend = new Person("Tom");
Person thief = new Person("Tim");
deal(new FriendComing(),friend); //output: say hello to Tom
deal(new ThiefComing(),thief); //output: call 110 to arrest Tim
}
}