LoginSignup
5
5

More than 5 years have passed since last update.

4日目 => デザインパターン(モジュールパターン)

Posted at

はじめに

昨日に引き続き、デザインパターン。2個目。

説明

モジュール

プロジェクトのコードを分割して組織化する。

オブジェクトリテラル

オブジェクトリテラルを使うことでコードをカプセル化し、体系化できる。

カプセル化 【 encapsulation 】

カプセル化とは、オブジェクト指向プログラミングが持つ特徴の一つ。
データとそれを操作する手続きを一体化して「オブジェクト」として定義し、
オブジェクト内の細かい仕様や構造を外部から隠蔽すること。
外部からは公開された手続きを利用することでしかデータを操作できないようにすることで、
個々のオブジェクトの独立性が高まる。

var moduleObj = {
  // 何らかの設定
  config: {
    max: 10,
    min: 0
  },

  // 設定を使っての処理
  checkSize: function(value){
    console.log("最大値: " + this.config.max);
    console.log("最小値: " + this.config.min);

    if(value <= this.config.max && value >= this.config.min){
      console.log("範囲内です。");
    }else{
      console.log("範囲外です。");
    }
  },

  // 設定変更用
  updateConfig: function(config){
    if(typeof config === "object"){
      this.config = config;
    }
  }
}

でもこのままだと、updateConfig使わなくても直接書き換えれちゃうな。
後々そこらへんの解決策は出てくるかな。

moduleObj.config = {max: 0, min: -10};

モジュールパターン

アプリケーションの他の部分が使うインターフェースだけ外部公開するようにする。

var module1 = (function(){
  // 設定
  var config = {
    max: 10,
    min: 0
  }

  return {
    // 設定を使っての処理
    checkSize: function(value){
      console.log("最大値: " + config.max);
      console.log("最小値: " + config.min);

      if(value <= config.max && value >= config.min){
        console.log("範囲内です。");
      }else{
        console.log("範囲外です。");
      }
    },

    // 設定変更用
    updateConfig: function(newConfig){
      if(typeof config === "object"){
        config = newConfig;
      }
    }
  }
}());

configが外側から直接変更できなくなった!
パブリックにするものだけreturnして返す。

おわりに

外から書き換えられちゃダメなものは隠蔽したり、決まった方法でしかアクセスできないようにする。
なるほど。
もっとモダンな書き方が本の後半に出てくるらしい。

参考

  • JavaScriptデザインパターン
5
5
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
5
5