Created
March 26, 2014 15:11
-
-
Save shimada-shunsuke/9785609 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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