1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

オブジェクト指向を取り入れたRのデザインパターン

Last updated at Posted at 2014-11-12

共通的な流れや処理がある場合、複数のScriptで書くより、親子のクラス関係を使って書いてしまおうと思ったのがきっかけ。
テンプレートパターンをRに取り入れてみました。

#実装

SuperClass
setRefClass("ModelSuper",
    fields=list(var1="character"),
    methods=list(
        execute = function() {
          commonsetting()
          subproc()
        },
        commonsetting=function() {
            print("共通処理")
        },
        subproc = function(){}
    ))

  • commonsetting():共通処理を行うFunction
  • subproc():各、子クラスがImplementsするFunction(親クラスでは空実装)
  • execute()にて、commonsetting()とsubproc()を実行
SubClass
modelSub01 <- setRefClass(
    "modelSub01",
    contains="ModelSuper",
    methods = list(
    subproc = function() {
        print("sub01");
    })
)

modelSub02 <- setRefClass(
    "ModelSub02",
    contains="modelSuper",
    methods = list(
    subproc = function() {
        print("sub02");
    })
)
  • subproc()に各子クラスで処理を変える
呼び出し側
modelclz <- modelSub01$new()
modelclz$execute()

modelclz <- modelSub02$new()
modelclz$execute()
  • newするクラスによって、subprocの処理が変わります。
  • commonは変わりません

#注意

  • R5クラスが利用できるVersionである必要があります
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?