Strategy Pattern
Allows one of a family of algorithms to be selected on-the-fly at run-time.
Problem:
public class Encryptor {
private String algorithmName;
private String plainText;
public Encryptor(String algorithmName){
this.algorithmName=algorithmName;
}
public void encrypt(String plainText){
if (algorithmName.equals("Aes")){
System.out.println("Encrypting data using AES algorithm");
AESEncryption.encrypt(plainText);
}
else if (algorithmName.equals("Blowfish")){
System.out.println("Encrypting data using Blowfish algorithm");
BlowFishEncryption.encrypt(plainText);
}
}
}
Client Class:
public class UserService {
public void encryptUserPassword(String password) {
Encryptor encryptor = new Encryptor("Aes");
encryptor.encrypt(password); //Encrypting with AES
}
public void encryptCreditCard(String creditCard) {
Encryptor encryptor = new Encryptor("BlowFish");
encryptor.encrypt(creditCard); //Encrypting with BlowFish
}
}
Strategy Pattern applied:
public interface EncryptionStrategy {
void encryptData(String plainText);
}
AES Encryption:
public class AesEncryptionStrategy implements EncryptionStrategy {
public void encryptData(String plaintext) {
System.out.println("-------Encrypting data using AES algorithm-------");
//Implementation of AES Encryption
}
}
BlowFish Encryption:
public class BlowFishEncryptionStrategy implements EncryptionStrategy {
public void encryptData(String plaintext) {
System.out.println("-------Encrypting data using BlowFish algorithm-------");
//Implementation of BlowFish Encryption
}
}
Encryptor
public class Encryptor {
private EncryptionStrategy strategy;
private String plainText;
public Encryptor(EncryptionStrategy strategy){
this.strategy=strategy;
}
public void encrypt(String planText){
strategy.encryptData(plainText);
}
}
Client Class:
public class UserService {
public void encryptUserPassword(String password) {
Encryptor encryptor = new Encryptor(AesEncryptionStrategy);
encryptor.encrypt(password); //Encrypting with AES
}
public void encryptCreditCard(String creditCard) {
Encryptor encryptor = new Encryptor(BlowFishEncryptionStrategy);
encryptor.encrypt(creditCard); //Encrypting with BlowFish
}
}