Created
October 27, 2014 04:44
-
-
Save kencharos/1518df9e660e2873b5fb to your computer and use it in GitHub Desktop.
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
/* | |
* Java8 デフォルト実装の使用例 | |
*/ | |
package defaultif; | |
import java.io.File; | |
import java.io.IOException; | |
import java.io.UncheckedIOException; | |
import java.nio.file.Files; | |
import java.nio.file.StandardOpenOption; | |
import java.util.Arrays; | |
/** Infoログ出力可能IF */ | |
interface InfoLog { | |
void info(String msg); | |
} | |
/** Errorログ出力可能IF */ | |
interface ErrorLog { | |
void error(String msg); | |
} | |
/** Infoログをコンソールに出す。 */ | |
interface InfoConsoleLog extends InfoLog{ | |
// デフォルトメソッドでオーバーライド可能。 | |
@Override default void info(String msg) { | |
System.out.println("info:" + msg); | |
} | |
} | |
/** errorログをコンソールに出す。 */ | |
interface ErrorConsoleLog extends ErrorLog{ | |
@Override default void error(String msg) { | |
System.out.println("error:" + msg); | |
} | |
} | |
/** errorログをファイルに出す。 */ | |
interface ErrorFileLog extends ErrorLog{ | |
@Override default void error(String msg) { | |
try { | |
Files.write(new File("error.log").toPath(), | |
Arrays.asList("error[" + this.getClass() + "]" + msg), | |
StandardOpenOption.APPEND, StandardOpenOption.CREATE); | |
} catch (IOException ex) { | |
throw new UncheckedIOException(ex); | |
} | |
} | |
} | |
/** なんらかの処理を行うクラス */ | |
// abstractなのは実装しているインターフェースの実装を避けるため。 | |
abstract class Process implements InfoLog, ErrorLog { | |
public void go() { | |
info("開始"); | |
// 何らかの処理。 | |
if(System.currentTimeMillis() % 2 == 0) { | |
//エラー | |
error("処理が失敗しました。"); | |
} else { | |
info("処理が正常終了しました。"); | |
} | |
} | |
} | |
// エラーログはコンソールに出す。定義のみでOK | |
class ProcessOnErrorLogToConsole extends Process implements InfoConsoleLog, ErrorConsoleLog{} | |
// エラーログはファイルに出す。 | |
class ProcessOnErrorLogToFile extends Process implements InfoConsoleLog, ErrorFileLog{} | |
public class DefaultExample { | |
public static void main(String[] args) { | |
//こんな書き方ができるいいのにな。→scalaでできるよ! | |
//Propces p1 = new Process implements InfoConsoleLog, ErrorConsoleLog(){}; | |
Process p = new ProcessOnErrorLogToFile(); | |
p.go(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment