Java中的策略模式浅析及回调函数

策略模式是对算法的包装,把使用算法的责任和算法本身分隔开,委派给不同的对象管理。
策略模式通常把一系列的算法包装到一系列的策略类里面,作为一个抽象策略类的子类。
何时使用策略模式:
1.如果在一个系统里面有许多类,他们之间的区别仅在于他们的行为,那么使用策略类可以动态的让一个对象在许多行为中选择一种行为。
2.如果系统需要动态的在几种算法中选择一种,那么这些算法可以具体的包装到一个个算法类里面,而这些算法类都是一个抽象类的子类。换言之这些具体的算法类均有统一的接口,由于多态性的原则,客户端可以选择使用任何一个具体的算法类,并只持有一个数据类型是抽象算法类的对象。
3.一个系统的算法使用的数据不可以让客户端知道。策略模式可以避免让客户涉及到不必要的算法和与算法相关的数据。
例子:
//策略接口
public interface Person {
?void speak();
}
//策略接口的实现类
public class Chinese implements Person {
?@Override
?public void speak() {
??System.out.println("----说汉语------");
?}
}
?
//策略接口的实现类
public class English implements Person {
?@Override
?public void speak() {
??System.out.println("---------speak english--------");
?}
}
?
//策略调用类
public class Strategy {
?private Person person;
?
?public Strategy(Person person){
??this.person = person;
?}
?
?public void speak(){
??person.speak();
?}
}
?
//测试类
public class Test {
?public static void main(String [] args){
??
??Person person = new Chinese();
??Strategy strategy = new Strategy(person);
??strategy.speak();
?}
}
?
?
=================================================================================
//策略接口
public interface Person {
?void speak();
}
?
//策略调用类
public class Strategy {
?public void execute(Person callback)
?{
??callback.speak();
?}?
}
?
//测试类
public class Test {
?public static void main(String [] args){
??
??Strategy strategy = new Strategy();
??
??//说汉语
??strategy.execute(new Person(){
????public void speak()? //?? execute(new doInhibernateCallBack(){ })
????{
?????System.out.println("--------说汉语--------");
????}
??});
??
??//说英语
??strategy.execute(new Person(){
???public void speak()? //?? execute(new doInhibernateCallBack(){ })
???{
????System.out.println("--------speak english--------");
???}
?});
?}
}