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

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

问题描述

我一直在阅读有关 OCP主要以及如何使用策略模式来实现这一点。

I've been reading about the OCP principal 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 like 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.

客户端code看起来是一样的:

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天全站免登陆