策略模式客户端实现问题

Strategy Pattern Client implementation problem

目前我有一个策略模式:

public interface EncryptionAlgorithm {
    String encrypt(String text);
}

public class Encrypter {
    private EncryptionAlgorithm encryptionAlgorithm;

    String encrypt(String text){
        return encryptionAlgorithm.encrypt(text);
    }

    public void setEncryptionAlgorithm(EncryptionAlgorithm encryptionAlgorithm) {
        this.encryptionAlgorithm = encryptionAlgorithm;
    }
}

public class UnicodeEncryptionAlgorithm implements EncryptionAlgorithm {
    @Override
    public String encrypt(String text) {
        return "";
    }
}

我希望客户端成为一个密码学家class,它将创建上下文(我也有一个解密器,与加密器一样),但我正在努力制作这些方法。

public class Cryptographer {

}

public class Main {
    public static void main(String[] args) {
        Cryptographer cryptographer = new Cryptographer();
        cryptographer.setCryptographer(new Encrypter());
        cryptographer.setAlgorithm(new UnicodeEncryptionAlgorithm());
    }
}

我试图让 Cryptographer 成为一个接口,并通过加密器实现这些方法,但没有成功。有什么建议吗?

EncryptionAlgorithm 是您的策略。所以这里的代码和你的一样。

public interface EncryptionAlgorithm {
    String encrypt(String text);
}

UnicodeEncryptionAlgorithm 是具体策略,这里是相同的代码。具体策略可以有n个。

public class UnicodeEncryptionAlgorithm implements EncryptionAlgorithm {
    @Override
    public String encrypt(String text) {
        return "";
    }
}

根据您的要求,Cryptographer 应该是上下文。我让它 CryptographerContext 更有意义。如果您愿意,可以更改名称。

public class CryptographerContext {

    private EncryptionAlgorithm encAlgo;

    public void setEncryptionStrategy(EncryptionAlgorithm encAlgo) {
        this.encAlgo = encAlgo;
    }

    public String getEncryptedContents(String text) {
        return encAlgo.encrypt(text);
    }
}

在上述情况下,您必须使用抽象策略。

我在下面主要提供class进行测试。如果有很多策略,您必须使用 context.setStrategy(concrete impl class).

设置最适合您需求的策略
public class Main {
  public static void main(String[] args) {
    CryptographerContext cryptographer = new CryptographerContext();
    cryptographer.setEncryptionStrategy(new UnicodeEncryptionAlgorithm());
    String encText = cryptographer.getEncryptedContents("some text");
    System.out.println("Encrypted text: "+encText);
  }
}