策略模式的真实世界示例 [英] Real World Example of the Strategy Pattern

查看:32
本文介绍了策略模式的真实世界示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读 OCP 原则 以及如何使用该策略模式来实现这一点.

I've been reading about the OCP principle and how to use the strategy pattern to accomplish this.

我打算尝试向几个人解释这一点,但我能想到的唯一示例是根据订单"的状态使用不同的验证类.是.

I was going to try and explain this to a couple of people, but the only example I can think of is using different validation classes based on what status an "order" is.

我在网上阅读了几篇文章,但这些文章通常没有描述使用该策略的真正相似原因,例如生成报告/账单/验证等...

I've read a couple of articles online, but these don't usually describe a real alike reason to use the strategy, like generating reports/bills/validation, etc...

在现实世界中,您是否认为战略模式很常见?

Are there any real-world examples where you think a strategy pattern is common?

推荐答案

关于这个:

您必须加密文件.

对于小文件,您可以使用内存中"策略,读取完整文件并将其保存在内存中(假设文件小于 1 gb)

For small files, you can use "in memory" strategy, where the complete file is read and kept in memory ( let's say for files < 1 gb )

对于大文件,您可以使用另一种策略,其中文件的一部分在内存中读取,部分加密结果存储在 tmp 文件中.

For large files, you can use another strategy, where parts of the file are read in memory and partial encrypted results are stored in tmp files.

对于同一任务,这可能是两种不同的策略.

These may be two different strategies for the same task.

客户端代码看起来是一样的:

The client code would look the same:

 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() );

将为密码返回正确的策略实例.

Would return the correct strategy instance for the cipher.

我希望这会有所帮助.

(我什至不知道密码是否正确:P)

这篇关于策略模式的真实世界示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆