设计模式之策略模式(java)

1、概念

定义了一个算法簇,对每个算法进行封装,使得算法之间可以相互代替。

2、 UML类图

3、java代码实现 

抽象策略角色:策略类,通常是一个接口或抽象类

public abstract class Strategy {

	public abstract void algorithmInterface();

}

具体策略角色A、B、C:包装了相关的算法和行为

public class ConcreteStrategyA extends Strategy {

	@Override
	public void algorithmInterface() {
		System.out.println("ConcreteStrategyA");
	}

}
public class ConcreteStrategyB extends Strategy {

	@Override
	public void algorithmInterface() {
		System.out.println("ConcreteStrategyB");
	}

}
public class ConcreteStrategyC extends Strategy {

	@Override
	public void algorithmInterface() {
		System.out.println("ConcreteStrategyC");
	}

}

 环境角色:维护一个策略类的引用,供客户端调用

public class Context {

	private Strategy strategy;

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

	public void contextInterface() {
		if (this.strategy != null) {
			strategy.algorithmInterface();
		}
	}

}

 测试

@Test
public void testStrategy() {
	Context contextA = new Context(new ConcreteStrategyA());
	contextA.contextInterface();
	Context contextB = new Context(new ConcreteStrategyB());
	contextB.contextInterface();
	Context contextC = new Context(new ConcreteStrategyC());
	contextC.contextInterface();
}

 测试结果

ConcreteStrategyA
ConcreteStrategyB
ConcreteStrategyC

以上代码实现了一个"策略模式"的案例,不过以上代码要求客户端知道具体使用哪个策略,之间存在耦合;可通过"简单工厂模式"修改环境角色的代码来实现解耦,具体代码如下

public class Context {

	private Strategy strategy;

	public Context(String type) {
		switch (type) {
			case "A" :
				this.strategy = new ConcreteStrategyA();
				break;
			case "B" :
				this.strategy = new ConcreteStrategyB();
				break;
			case "C" :
				this.strategy = new ConcreteStrategyC();
				break;
		}
	}

	public void contextInterface() {
		if (this.strategy != null) {
			strategy.algorithmInterface();
		}
	}

}

测试

@Test
public void testStrategy() {
	Context contextA = new Context("A");
	contextA.contextInterface();
	Context contextB = new Context("B");
	contextB.contextInterface();
	Context contextC = new Context("C");
	contextC.contextInterface();
}

测试结果

ConcreteStrategyA
ConcreteStrategyB
ConcreteStrategyC

4、总结

优点:提供管理相关算法簇的方法;提供可以替换继承关系的方法;避免使用多重条件转移语句。

缺点:客户端必须知道所有的策略类,并自行决定使用哪一个策略类;策略模式造成很多的策略类,每个具体策略类都会产生一个新类。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值