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

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

问题描述

我一直在阅读 OCP主体以及如何使用策略模式要完成这个。



我将尝试向几个人解释这一点,但是我可以想到的唯一的例子是根据什么状态使用不同的验证类订单是。



我已经在线阅读了几篇文章,但这些通常不会描述一个真正的理由来使用该策略,例如生成报告/ bill / validation etc ...



有没有任何真实世界的例子,你认为策略模式是常见的?

解决方案

这是什么:



你必须加密一个文件。



对于小文件,您可以使用内存策略,其中完整的文件被读取并保存在内存中(假设文件为< 1 gb) p>

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



这些可能是同一个任务的两种不同的策略。



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

 文件文件= getFile(); 
密码c = CipherFactory.getCipher(file.size());
c.performAction();



//实现:
接口Cipher {
public void performAction();
}

class InMemoryCipherStrategy实现Cipher {
public void performAction(){
// load in byte [] ....
}
}

类SwaptToDiskCipher实现Cipher {
public void performAction(){
//将部分结果转换为文件。
}

}

  Cipher c = CipherFactory.getCipher(file.size()); 

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


$ b $我希望这有帮助。



(我甚至不知道密码是否是正确的词:P)


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?

解决方案

What about this:

You have to encrypt a file.

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 )

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.
         }

}

The

     Cipher c = CipherFactory.getCipher( file.size() );

Would return the correct strategy instance for the cipher.

I hope this helps.

( I don't even know if Cipher is the right word :P )

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

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