设计模式3: Strategy模式
看下面的实例, 程序中需要有不同的对日期格式化的方法。
Strategy模式的思路如下:
1. 定义格式化日期的抽象接口
2. 不同的格式化类实现该接口
3. 客户类BillingSystem可以保存格式化的接口引用。
好处是显而易见的,修改添加格式化方法的时候,客户类不需要改变。
interface DateFormatStrategy {
String format_date( Date d );
}
class BillingSystem {
private DateFormatStrategy formatter = null;
public void set_format( DateFormatStrategy dfs ) {
formatter = dfs;
}
public void print_statement( Date now ) {
if (formatter == null)
System.out.println( now.toString() );
else
System.out.println( formatter.format_date( now ) );
} }
public class StrategyDemo {
public static void main( String[] args ) {
BillingSystem the_client = new BillingSystem();
Date today = new Date();
the_client.print_statement( today );
the_client.set_format( new ShortUnitedKingdomStrategy() );
the_client.print_statement( today );
} }
http://www.vincehuston.org/dp/strategy.html
本文由IT Farmer的博客创作,欢迎转载并保留对本博的链接。 Tags:design pattern,设计模式