策略模式和上下文 class

Strategy Pattern and context class

阅读有关策略设计模式的内容,正在考虑是否可以有两个上下文。

如果下面的代码设计使用策略设计模式,期待意见。

或者策略设计模式强制我们只有一个上下文,这意味着下面的设计是不正确的。

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

}

Strategy Pattern 旨在以多种方式实现算法,而客户不会知道其细节。在您的示例中, EncryptionDecryption 是两个不同的上下文,因此它们将做两件不同的事情。假设您的客户端将使用 Cryptography 接口,您需要定义 encryptdecrypt 方法。在这种情况下,您强制 EncryptionContext class 实施 decryptDecryptionContext class 实施 encrypt 方法,这是不正确的。这就是为什么,我不认为这种设计与策略模式相结合。

Algorithm 中使用了策略,但是对于您的示例来说,它有点强制,因为它不是强制性地绑定 ContructorAlgorithm

这只是一个如何使用 Strategy.

的基本示例
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
   
}