Created
October 14, 2011 08:40
-
-
Save belun/1286579 to your computer and use it in GitHub Desktop.
DSL example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Input { | |
public static MaskableInput filteredBy(Mask mask) { | |
return new MaskableInput(mask); | |
} | |
static class MaskableInput { | |
private Mask mask; | |
private MaskableInput(Mask mask) { | |
this.mask = mask; | |
} | |
public TransformableInput transformedBy(Transformation transformation) { | |
return new TransformableInput(transformation); | |
} | |
class TransformableInput { | |
private final Transformation transformation; | |
private TransformableInput(Transformation transformation) { | |
this.transformation = transformation; | |
} | |
public ValuedInput valueOf(InitialValue initialAmount) { | |
return new ValuedInput(initialAmount.asText()); | |
} | |
class ValuedInput implements Showable { | |
private final String text; | |
private ValuedInput(String text) { | |
this.text = text; | |
} | |
public ValuedInput valueOf(String text) { | |
return new ValuedInput(text); | |
} | |
@Override | |
public void showInto(JFormattedTextField inputField) { | |
String filteredInput = MaskableInput.this.mask.applyTo(this.text); | |
new OutputFactory().buildFrom(filteredInput).showInto(inputField); | |
} | |
class OutputFactory { | |
public Showable buildFrom(String input) { | |
return (input.isEmpty()) ? new FixedOutput(input) : new TransformedOutput(input); | |
} | |
} | |
class FixedOutput implements Showable { | |
private final String value; | |
private FixedOutput(String value) { | |
this.value = value; | |
} | |
@Override | |
public void showInto(JFormattedTextField inputField) { | |
// reset the internal value of the JFormattedTextField and just put text | |
inputField.setValue(null); | |
inputField.setText(this.value); | |
// clear previous results | |
TransformableInput.this.transformation.reset(); | |
} | |
} | |
class TransformedOutput implements Showable { | |
private final String input; | |
private TransformedOutput(String input) { | |
this.input = input; | |
} | |
@Override | |
public void showInto(JFormattedTextField inputField) { | |
Object transformedInput = TransformableInput.this.transformation.from(this.input); | |
inputField.setValue(transformedInput); | |
} | |
} | |
} | |
} | |
} | |
} | |
// Initialized as: | |
ValuedInput input = Input.filteredBy(mask).transformedBy(transformation).valueOf(initialAmount) | |
// Recreated as: | |
input = input.valueOf(newAmmount); | |
// Used as: | |
input.showInto(formattedTextField) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment