首页 > 其他 > 详细

设计模式之七:Strategy(策略)—对象行为型模式

时间:2014-03-26 06:33:16      阅读:512      评论:0      收藏:0      [点我收藏+]

2014-03-23 星期日 21:19:26 bubuko.com,布布扣bubuko.com,布布扣

Strategy,继续GOF。

1、Intent

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

定义一系列的算法 ,把它们一个个封装起来 ,  并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。

2、Also Known As

Policy(政策/方针)

3、Motivation

Many algorithms exist for breaking a stream of text into lines. Hard-wiring all such algorithms into the classes that require them isn‘t desirable for several reasons:

●  Clients that need linebreaking get more complex if they include the linebreaking code. That makes clients bigger and harder to maintain, especially if they support multiple linebreaking algorithms.

●  Different algorithms will be appropriate at different times. We don‘t want to support multiple linebreaking algorithms if we don‘t use them all.

●  It‘s difficult to add new algorithms and vary existing ones when linebreaking is an integral part of a client.

有许多算法可对一个正文流进行分行。将这些算法硬编进使用它们的类中是不可取的,其原因如下 :

 需要换行功能的客户程序如果直接包含换行算法代码的话将会变得复杂,这使得客户程序庞大并且难以维护 ,  尤其当其需要支持多种换行算法时问题会更加严重。

 不同的时候需要不同的算法,我们不想支持我们并不使用的换行算法。

 当换行功能是客户程序的一个难以分割的成分时 , 增加新的换行算法或改变现有算法将十分困难。

我们可以定义一些类来封装不同的换行算法,从而避免这些问题。一个以这种方法封装的算法称为一个策略( s t r a t e g y ),如下图所示。

bubuko.com,布布扣

4、Applicability

Use the Builder pattern when

●  many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors.

●  you need different variants of an algorithm. For example, you might define algorithms reflecting different space/time trade-offs. Strategies can be used when these variants are implemented as a class hierarchy of algorithms [HO87].

?●  an algorithm uses data that clients shouldn‘t know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures.

?●  a class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class.

在以下情况使用Strategy模式

 许多相关的类仅仅是行为有异。 “策略”提供了一种用多个行为中的一个行为来配置一个类的方法。

● 需要使用一个算法的不同变体。例如,你可能会定义一些反映不同的空间 / 时间权衡的算法。当这些变体实现为一个算法的类层次时 [ H O 8 7 ] ,可以使用策略模式。

● 算法使用客户不应该知道的数据。可使用策略模式以避免暴露复杂的、与算法相关的数据结构。

 一个类定义了多种行为 ,  并且这些行为在这个类的操作中以多个条件语句的形式出现。将相关的条件分支移入它们各自的 S t r a t e g y类中以代替这些条件语句。

5、Structure

?bubuko.com,布布扣

6、代码

?见Bridge模式。






设计模式之七:Strategy(策略)—对象行为型模式,布布扣,bubuko.com

设计模式之七:Strategy(策略)—对象行为型模式

原文:http://www.cnblogs.com/freezlz/p/3624163.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!