Java 策略模式与语境类
阅读有关策略设计模式的文章时,正在思考是否可能有两种背景 期待以下代码设计是否使用策略设计模式的意见 或者策略设计模式迫使我们只有一个上下文,这意味着下面的设计是不正确的Java 策略模式与语境类,java,design-patterns,strategy-pattern,Java,Design Patterns,Strategy Pattern,阅读有关策略设计模式的文章时,正在思考是否可能有两种背景 期待以下代码设计是否使用策略设计模式的意见 或者策略设计模式迫使我们只有一个上下文,这意味着下面的设计是不正确的 public interface Algorithm {} public class FirstAlgorithm implements Algorithm {} public class SecondAlgorithm implements Algorithm {} public interface Cryptograp
public interface Algorithm {}
public class FirstAlgorithm implements Algorithm {}
public class SecondAlgorithm implements Algorithm {}
public interface Cryptography {}
public class DecryptionContext implements Cryptography {
public DecryptionContext(Algorithm algorithm) {
this.algorithm = algorithm;
}
}
public class EncryptionContext implements Cryptography {
public EncryptionContext(Algorithm algorithm) {
this.algorithm = algorithm;
}
}
策略模式旨在以多种方式实现算法,而客户机不知道其细节。在您的示例中,
加密
和解密
是两种不同的上下文,因此它们将执行两种不同的操作。假设您的客户端将使用加密
接口,您需要定义加密
和解密
方法。在这种情况下,您强制EncryptionContext
类实现decrypt
并强制DecryptionContext
类实现不正确的encrypt
方法。这就是为什么,我不认为这种设计与策略模式相结合。在算法中使用了策略,但在您的示例中,它有点强制,因为它不是强制要求将构造函数
与算法
绑定的,它只是如何使用策略的一个基本示例
public interface Algorithm
{
public String doOperation(...);
}
public class FirstAlgorithm implements Algorithm { ... decrypt ...}
public class SecondAlgorithm implements Algorithm { ... encrypt ...}
//public interface Cryptography {}
//another option is to implement Algorithm on both Enc/Dec - class,
//it's only of your design and purpose
public class DecryptionContext {
...
public DecryptionContext(Algorithm algorithm,String strEncrypt)
{
this.algorithm = algorithm;
...
}
}
public class EncryptionContext {
public EncryptionContext(Algorithm algorithm, String strDecrypt) {
this.algorithm = algorithm;
...
}
}
class Main
{
...
Algorithm ae = new SecondAlgorithm();
EncryptionContext ec = new EncryptionContext(ae, "abc");
//this op can be done even inside EncryptionContext ... but the purpose is understanding strategy
String res = ec.ae.doOperation(ec.strDecrypt); //abc -> efg
//since only need input string could be rewrite as
//String res = ae.doOperation(ec.strDecrypt)
ae = new FirstAlgorithm();
DecryptionContext dc = new DencryptionContext(ae, res);
res = dc.ae.doOperation(dc.strEncrypt); //efg->abc
}
每个算法有两个类,一个用于加密,另一个用于解密。使用DecryptionContext和EncryptionContext类作为上下文使用策略模式是否正确?是ae.doOperation(string)
-加密或解密取决于ae
的设置方式(第一个或第二个Alg
)。这是策略。(不要有两个单独的操作,只有一个可以同时执行这两个操作取决于设置)我接受你的回答,你能提供一个更高级的策略设计模式示例吗,如果这里没有,至少提供一个链接,因为你提到“这只是如何使用策略的一个基本示例。”作为教程,互联网上有很多,可能有以下链接:。作为一本书,有一本是用来学习的,也许你们可以找到它:“Java中的模式:用UML说明的可重用设计模式目录,第二版,第一卷,马克·格兰德的第二版”。在我看来最好的一个是关于。。。享受学习的乐趣!