Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Trancoder example - Java Flavour
package Transcoding;
public class ASCIIDecimalCodeTranscoderStrategy implements TranscoderStrategy {
@Override
public String transcode(String message) {
return (message + ": to ASCII Code ");
}
}
package Transcoding;
public class BrailleTranscoderStrategy implements TranscoderStrategy {
@Override
public String transcode(String message) {
return (message+": to Brailling ");
}
}
package Transcoding;
public class EncryptTranscoderStrategy implements TranscoderStrategy {
@Override
public String transcode(String message) {
return (message+": to Encrypt code ");
}
}
package Transcoding;
public class Main {
public static void main(String[] args) {
TranscoderStrategy transcoderStrategies[] = {
new BrailleTranscoderStrategy(),
new EncryptTranscoderStrategy(),
new MorseTranscoderStrategyStrategy()};
TranscoderStrategy asciiDecimalCodeTranscoderStrategy = new ASCIIDecimalCodeTranscoderStrategy();
TranscodingTextService transcodingTextService = new TranscodingTextService(asciiDecimalCodeTranscoderStrategy);
String message = "Meessage to translate";
System.out.println("TranscodingTextService is using the behavior injected by constructor...\n\t"+ transcodingTextService.execute(message));
System.out.println("\nTranscodingTextService can change its behavior dinamicaly by setter...");
for (int i = 0; i < transcoderStrategies.length; i++) {
transcodingTextService.setTranscoderStrategy(transcoderStrategies[i]);
String result = transcodingTextService.execute(message);
System.out.println("\t" + result);
}
}
}
package Transcoding;
public class MorseTranscoderStrategyStrategy implements TranscoderStrategy {
@Override
public String transcode(String message) {
return (message + ": to Morse Code ");
}
}
package Transcoding;
public interface TranscoderStrategy {
public String transcode(String source);
}
package Transcoding;
public class TranscodingTextService {
private TranscoderStrategy transcoderStrategy;
public TranscodingTextService(TranscoderStrategy transcoderStrategy) {
this.transcoderStrategy = transcoderStrategy;
}
public String execute(String message) {
return transcoderStrategy.transcode(message);
}
public void setTranscoderStrategy(TranscoderStrategy transcoderStrategy) {
this.transcoderStrategy = transcoderStrategy;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment