martinfowler.com流し読み - FunctionAsObject
はじめに
最近、https://martinfowler.com/tags から過去の全ての投稿を閲覧できることを発見したので、新しいものから順に遡って読むことにした。
いつまで続くかはわからない。
本日のエントリ
概要
- 第一級関数とクロージャを持つ言語では、Function As Objectパターンを使ってオブジェクトを生成することができる。
- このパターンでは、コンストラクタ関数がメソッドセレクタとして機能する関数のハッシュマップを返す。これは古典的なオブジェクトのように扱うことができる。
- 戻り値のメソッドセレクタにはハッシュマップでなく関数を利用することもできる。
コード例
JavaScriptでの実装例(元エントリのコードを引用)。
function createPerson(name) { let birthday; return { name: () => name, setName: (aString) => name = aString, birthday: () => birthday, setBirthday: (aLocalDate) => birthday = aLocalDate, age: age, canTrust: canTrust, }; function age() { return birthday.until(clock.today(), ChronoUnit.YEARS); } function canTrust() { return age() <= 30; } }
このコンストラクタ関数を次のようにして利用する。
const kent = createPerson("kent"); kent.setBirthday(LocalDate.parse("1961-03-31")); const youngEnoughToTrust = kent.canTrust();
感想
メソッドセレクタとしての関数、
To use a function as the method selector, I’d return a function whose first argument is the name of the method to invoke. The function body then switches on that value (see Wallingford for more on this).
と書かれているので、object('methodName')(args)
みたいな感じになるのだろうか。
さらに知りたい場合
Eugene Wallingford氏の論文がオススメとのこと。
ただし例は全てSchemeで書かれている。