Skip to content

Instantly share code, notes, and snippets.

@shimada-shunsuke
Created March 26, 2014 15:11
Show Gist options
  • Save shimada-shunsuke/9785609 to your computer and use it in GitHub Desktop.
Save shimada-shunsuke/9785609 to your computer and use it in GitHub Desktop.
abstract class Process {
public abstract void run() throws ProcessFailure;
public Process and(final Process other) {
final Process self = this;
return new Process() {
public void run() throws ProcessFailure {
self.run();
other.run();
}
};
}
public Process or(final Process other) {
final Process self = this;
return new Process() {
public void run() throws ProcessFailure {
try {
self.run();
} catch(ProcessFailure e) {
other.run();
}
}
};
}
}
class ProcessFailure extends Exception {
}
class Printer extends Process{
private final String text;
private final boolean success;
public Printer(final String text, final boolean success) {
this.text = text;
this.success = success;
}
public void run() throws ProcessFailure {
final String result = success ? "success" : "fail";
System.out.println(text + ": " + result);
if(! success)
throw new ProcessFailure();
}
}
public class Processes {
private static final Printer printA = new Printer("A", false);
private static final Printer printB = new Printer("B", false);
private static final Printer printC = new Printer("C", false);
private static final Printer printD = new Printer("D", true);
public static void main(final String[] args) {
try {
printA.or(printB).or(printC).and(printD).run();
} catch (ProcessFailure e) {
System.out.println("Sorry!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment