读书人

设计形式之 Strategy - 策略模式

发布时间: 2012-09-17 12:06:51 作者: rapoo

设计模式之 Strategy - 策略模式
Strategy模式也叫策略模式,是由GoF提出的23种软件设计模式的一种。 Strategy模式是行为模式之一,它对一系列的算法加以封装,为所有算法定义一个抽象的算法接口,并通过继承该抽象算法接口对所有的算法加以封装和实现,具体的算法选择交由客户端决定(策略)。Strategy模式主要用来平滑地处理算法的切换。
本文介绍设计模式中的(Strategy)模式的概念,用法,以及实际应用中怎么样使用Strategy模式进行开发。

Strategy模式的角色:
Strategy
????策略(算法)抽象。
ConcreteStrategy
????各种策略(算法)的具体实现。
Context
????策略的外部封装类,或者说策略的容器类。根据不同策略执行不同的行为。策略由外部环境决定。


package zieckey.designpatterns.study.strategy;

/**
?*
?* 客户端测试程序。
?* @author zieckey
?*
?*/
public class Client
{
????public static void main( String[] argv )
????{
????????//2种不同的策略

????
???? //使用DES策略(算法)

???? EncryptContext context = new EncryptContext(new DesStrategy());
???? context.encrypt();
????
???? //使用MD5策略(算法)

???? context = new EncryptContext(new MD5Strategy());
???? context.encrypt();
????}
}


package zieckey.designpatterns.study.strategy;

/**
?*
?* Context
?*
?* 给客户端调用的
?*
?* @author zieckey
?* @since 2008/06/21
?*/
public class EncryptContext
{
????IEncryptStrategy????strategy;

????public EncryptContext( IEncryptStrategy strategy )
????{
????????this.strategy = strategy;
????}
????
????//执行具体的策略行为

????public void encrypt()
????{
????????strategy.encrypt();
????}
}






package zieckey.designpatterns.study.strategy;

/**
?*
?* 加密算法接口。
?* 所有的加密算法都必须实现该接口。
?* 如果新增一个加密算法,那么只需要实现该接口,而现有的程序代码都不用改变。
?*
?* @author zieckey
?* @since 2008/06/21
?*/
public interface IEncryptStrategy
{
????public void encrypt();//加密算法

}






package zieckey.designpatterns.study.strategy;

/**
?* 具体的加密算法
?* @author zieckey
?*
?*/
public class MD5Strategy implements IEncryptStrategy
{
????public void encrypt()
????{
????????System.out.println( "encrypt by MD5 algorithm." );
????????//TODO MD5 algorithm HERE。这里我们没给出具体的算法。

????}
}





package zieckey.designpatterns.study.strategy;

/**
?* 具体的加密算法
?* @author zieckey
?*
?*/
public class DesStrategy implements IEncryptStrategy
{
????public void encrypt()
????{
????????System.out.println( "encrypt by DES algorithm." );
????????//TODO DES algorithm HERE。这里我们没给出具体的算法。

????}
}


测试输出:

encrypt by DES algorithm.
encrypt by MD5 algorithm.


参考:
http://www.lifevv.com/sysdesign/doc/20071203214955037.html
http://www.cnblogs.com/justinw/archive/2007/02/06/641414.html

读书人网 >软件开发

热点推荐