Skip to content

Instantly share code, notes, and snippets.

@koji-k
Last active February 28, 2017 16:58
Show Gist options
  • Save koji-k/db210b4da4cb44d4875edaf8e2b072b3 to your computer and use it in GitHub Desktop.
Save koji-k/db210b4da4cb44d4875edaf8e2b072b3 to your computer and use it in GitHub Desktop.
委譲のサンプル
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")
@koji-k
Copy link
Author

koji-k commented Feb 28, 2017

MyStorageはあくまで「何か保存しておいて」というお願いを聞くのみ。実際の保存処理は別のクラスで行う。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment