Package : strategy
Interface : EncodingStrategy
Class : NormarStrategy, Base64Strategy, Encoder, AppendStrategy
EncodingStrategy.java
package com.company.design.strategy;
public interface EncodingStrategy {
String encode(String text);
}
package com.company.design.strategy;
public class NormarStrategy implements EncodingStrategy{
@Override
public String encode(String text) {
return text;
}
}
package com.company.design.strategy;
import java.util.Base64;
public class Base64Strategy implements EncodingStrategy{
@Override
public String encode(String text) {
return Base64.getEncoder().encodeToString(text.getBytes());
}
}
package com.company.design.strategy;
public class Encoder {
private EncodingStrategy encodingStrategy;
public String getMessage(String message) {
return this.encodingStrategy.encode(message);
}
public void setEncodingStrategy(EncodingStrategy encodingStrategy) {
this.encodingStrategy = encodingStrategy;
}
}
package com.company.design;
import com.company.design.strategy.Base64Strategy;
import com.company.design.strategy.Encoder;
import com.company.design.strategy.EncodingStrategy;
import com.company.design.strategy.NormarStrategy;
public class Main {
public static void main(String[] args) {
Encoder encoder = new Encoder();
// base64
EncodingStrategy base64 = new Base64Strategy();
// normal
EncodingStrategy normal = new NormarStrategy();
String message = "hello java";
encoder.setEncodingStrategy(base64);
String base64Result = encoder.getMessage(message);
System.out.println(base64Result);
encoder.setEncodingStrategy(normal);
String normalResult = encoder.getMessage(message);
System.out.println(normalResult);
}
}
package com.company.design.strategy;
public class AppendStrategy implements EncodingStrategy{
@Override
public String encode(String text) {
return "ABCD"+text;
}
}
package com.company.design;
import com.company.design.strategy.*;
public class Main {
public static void main(String[] args) {
Encoder encoder = new Encoder();
// base64
EncodingStrategy base64 = new Base64Strategy();
// normal
EncodingStrategy normal = new NormarStrategy();
String message = "hello java";
encoder.setEncodingStrategy(base64);
String base64Result = encoder.getMessage(message);
System.out.println(base64Result);
encoder.setEncodingStrategy(normal);
String normalResult = encoder.getMessage(message);
System.out.println(normalResult);
encoder.setEncodingStrategy(new AppendStrategy());
String appendResult = encoder.getMessage(message);
System.out.println(appendResult);
}
}