代码改变世界

设计模式之策略模式

2011-02-10 17:59  hanwesley  阅读(251)  评论(0编辑  收藏  举报

具体策略运行时刻自由切换

package org.springframework.samples.jpetstore.dp.strategy;

//策略抽象类
abstract class Strategy {
	public abstract void operator();
}

// 具体算法实现1
class ConcreateAStrategy extends Strategy {
	public void operator() {
		System.out.println("ConcreateAStrategy");
	}
}

// 具体算法实现2
class ConcreateBStrategy extends Strategy {
	public void operator() {
		System.out.println("ConcreateBStrategy");
	}
}

/**
 * 策略应用上下文
 */
class Context {
	private Strategy strategy;

	public Context(Strategy strategy) {
		this.strategy = strategy;
	}

	public void operator() {
		strategy.operator();
	}
}

public class StrategyMain {
	public static void main(String[] args) {
		Context contextA = new Context(new ConcreateAStrategy());
		contextA.operator();
		//应用上下文需要传入具体的实现算法,可以是已经实现的具体算法
		//JDK中的比较器就是用策略模式实现的
		Context contextB = new Context(new Strategy() {
			public void operator() {
				System.out.println("匿名内部类实现算法");
			}
		});
		contextB.operator();
	}
}