Last active
February 28, 2017 16:58
-
-
Save koji-k/db210b4da4cb44d4875edaf8e2b072b3 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
trait Persistence { | |
abstract Boolean save(String text) | |
} | |
class Cloud implements Persistence { | |
Boolean save(String text) { | |
println "save to cloud: ${text}" | |
} | |
} | |
class RDBMS implements Persistence { | |
Boolean save(String text) { | |
println "save to RDBMS: ${text}" | |
} | |
} | |
class Text implements Persistence { | |
Boolean save(String text) { | |
println "save to Text file: ${text}" | |
} | |
} | |
// このクラス自体は保存する責務が無い(というか出来ない)ので、他のクラスに実際の保存処理をお願いする(つまり委譲) | |
class MyStorage { | |
// ココはnewしてるけど本当はDIするのがベター | |
Persistence o = new Cloud() | |
Boolean save(String text) { | |
o.save(text) // この部分が所謂"委譲"になる。 | |
} | |
} | |
def obj = new MyStorage() | |
obj.save("Please save this text") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MyStorageはあくまで「何か保存しておいて」というお願いを聞くのみ。実際の保存処理は別のクラスで行う。