我一直在阅读有关OCP principle以及如何使用策略模式来实现这一点的文章。
我打算试着向几个人解释这一点,但我能想到的唯一例子是根据“订单”的状态使用不同的验证类。
我在网上读了几篇文章,但这些文章通常不会描述使用该策略的真正相似的原因,比如生成报告/账单/验证等。
您认为策略模式在现实世界中很常见吗?
发布于 2008-12-16 01:40:38
这样如何:
你必须加密一个文件。
对于小文件,您可以使用"in memory“策略,即读取完整的文件并将其保存在内存中(例如,对于小于1 gb的文件)
对于大文件,您可以使用另一种策略,即在内存中读取文件的某些部分,并将部分加密结果存储在临时文件中。
对于同一任务,这可能是两种不同的策略。
客户端代码看起来是一样的:
File file = getFile();
Cipher c = CipherFactory.getCipher( file.size() );
c.performAction();
// implementations:
interface Cipher {
public void performAction();
}
class InMemoryCipherStrategy implements Cipher {
public void performAction() {
// load in byte[] ....
}
}
class SwaptToDiskCipher implements Cipher {
public void performAction() {
// swapt partial results to file.
}
}这个
Cipher c = CipherFactory.getCipher( file.size() );将返回密码的正确策略实例。
我希望这能帮到你。
(我甚至不知道Cipher是不是正确的词:P )
发布于 2014-01-16 22:57:09
同样,这是一个旧帖子,但仍然出现在搜索结果中,所以我将再添加两个示例(代码在C#中)。我绝对喜欢Strategy模式,因为当项目经理说:“我们希望应用程序做'X',但'X‘还不清楚,它可以在不久的将来改变时,它省去了我的很多麻烦。”此video explaining the strategy pattern以StarCraft为例。
属于这一类的东西:
示例
我有一个项目,其中用户可以分配产品给数据库中的人。将产品分配给人员的状态为“已批准”或“已拒绝”,这取决于某些业务规则。例如:如果用户将某个产品分配给某个年龄的人,则该产品的状态应被拒绝;如果该项目中的两个字段之间的差值大于50,则该产品的状态为被拒绝,等等。
现在,在开发的时刻,这些业务规则还不是完全清楚的,新的规则随时都可能出现。策略模式的强大之处在于,我创建了一个RuleAgent,它提供了一个IRules列表。
public interface IRule {
bool IsApproved(Assignment assignment);
}在将产品分配给person时,我创建了一个RuleAgent,给它一个规则列表(所有规则都实现了IRule),并要求它验证分配。它会遵循所有的规则。因为它们都实现了相同的接口,所以它们都有IsApproved方法,如果它们中的任何一个返回false,都会返回false。
现在,例如,当经理突然出现并说,我们也需要拒绝实习生的所有任务,或所有加班人员的任务……您可以像这样创建新类:
public OvertimeRule : IRule
{
public bool IsApproved(Assignment assignment) //Interface method
{
if (assignment.Person.Timesheet >= 40)
{
return false;
}
return true;
}
}
public InternRule : IRule
{
public bool IsApproved(Assignment assignment) //Interface method
{
if (assignment.Person.Title == "Intern")
{
return false;
}
return true;
}
}您可以看到,不必不断添加或删除if语句或代码,只需创建一个实现IRUle接口的新规则类,并在需要时将其切换出来。
另一个很好的例子: Scott Allen在http://www.asp.net/mvc/pluralsight上的视频系列,他在应用程序的单元测试部分使用了策略模式
他建立了一个网站,其中有一个根据受欢迎程度显示项目的页面。然而,“流行”可以是很多东西(最多的视图,最多的订阅者,创建日期,最多的活动,最少的评论,等等),以防管理层还不知道如何确切地排序,并可能希望在以后尝试不同的排序。您可以使用order方法创建一个接口(IOrderAlgorithm或其他方法),并让order-object将排序委托给IOrderAlgorithm接口的具体实现。你可以创建一个"CommentOrderer","ActivityOrderer“等等...当有新的需求出现时,就把它们换掉。
发布于 2016-02-03 22:52:31
关键说明:
来自wikipedia的UML图

一个真实的例子:航空公司在某些月份(7月至12月)提供折扣。您可以有一个票价模块,它根据月份数字决定定价选项。
来看一个简单的例子。这个示例可以扩展到在线零售应用程序,它可以很容易地在特殊日子/快乐时间为购物车项目提供折扣。
import java.util.*;
/* Interface for Strategy */
interface OfferStrategy {
public String getName();
public double getDiscountPercentage();
}
/* Concrete implementation of base Strategy */
class NoDiscountStrategy implements OfferStrategy{
public String getName(){
return this.getClass().getName();
}
public double getDiscountPercentage(){
return 0;
}
}
/* Concrete implementation of base Strategy */
class QuarterDiscountStrategy implements OfferStrategy{
public String getName(){
return this.getClass().getName();
}
public double getDiscountPercentage(){
return 0.25;
}
}
/* Context is optional. But if it is present, it acts as single point of contact
for client.
Multiple uses of Context
1. It can populate data to execute an operation of strategy
2. It can take independent decision on Strategy creation.
3. In absence of Context, client should be aware of concrete strategies. Context acts a wrapper and hides internals
4. Code re-factoring will become easy
*/
class StrategyContext {
double price; // price for some item or air ticket etc.
Map<String,OfferStrategy> strategyContext = new HashMap<String,OfferStrategy>();
StrategyContext(double price){
this.price= price;
strategyContext.put(NoDiscountStrategy.class.getName(),new NoDiscountStrategy());
strategyContext.put(QuarterDiscountStrategy.class.getName(),new QuarterDiscountStrategy());
}
public void applyStrategy(OfferStrategy strategy){
/*
Currently applyStrategy has simple implementation. You can use Context for populating some more information,
which is required to call a particular operation
*/
System.out.println("Price before offer :"+price);
double finalPrice = price - (price*strategy.getDiscountPercentage());
System.out.println("Price after offer:"+finalPrice);
}
public OfferStrategy getStrategy(int monthNo){
/*
In absence of this Context method, client has to import relevant concrete Strategies everywhere.
Context acts as single point of contact for the Client to get relevant Strategy
*/
if ( monthNo < 6 ) {
return strategyContext.get(NoDiscountStrategy.class.getName());
}else{
return strategyContext.get(QuarterDiscountStrategy.class.getName());
}
}
}
public class StrategyDemo{
public static void main(String args[]){
StrategyContext context = new StrategyContext(100);
System.out.println("Enter month number between 1 and 12");
int month = Integer.parseInt(args[0]);
System.out.println("Month ="+month);
OfferStrategy strategy = context.getStrategy(month);
context.applyStrategy(strategy);
}
}输出:
Enter month number between 1 and 12
Month =1
Price before offer :100.0
Price after offer:100.0
Enter month number between 1 and 12
Month =7
Price before offer :100.0
Price after offer:75.0有用的文章:
按数据区划分的strategy模式
源码生成的strategy模式
https://stackoverflow.com/questions/370258
复制相似问题