策略模式和装饰模式的根本区别可以用一个形象的比喻来说明:
策略模式--外表没有变,但心(本质)变了;
装饰模式--外表变了,但心(本质)没有变。
使用策略模式可以动态地让一个对象在许多行为中选择一种行为,以下列举一个简单的策略模式例子:
//Person.java 策略接口
public interface Person {
public void speakLanguage();
}
//Chinese.java策略接口的实现类
public class Chinese implements Person {
public void speakLanguage() {
System.err.println("I speak Chinese!");
}
}
//StrategyPerson.java 策略调用类
public class StrategyPerson {
private Person person;
public StrategyPerson(Person person){
this.person = person;
}
public void speakLanguage(){
person.speakLanguage();
}
}
//TestMain.java 测试类
public class TestMain {
public static void main(String[] args){
Person person = new Chinese();
StrategyPerson sp = new StrategyPerson(person);
sp.speakLanguage();
}
}
浙公网安备 33010602011771号