S11. design patterns

1 분 소요

Design Patterns

  • 패턴이란?
    여러가지 서로 다른 상황에서 사용할 수 있는 템플릿 (재사용할 수 있는 솔루션)

  • 패턴의 이점
    • 검증이 되있다.
    • 재사용 가능하다.
    • 좋은 표현수단을 제공한다.
  • 객체생성패턴
    • 모듈 패턴 : 독립적 유닛
      • Object Literals
    • 재사용 패턴
  • 모듈 패턴
// 1-1. Object Literals : 가장 많이 쓰이고, 이걸 응용하는 패턴이 많다. 
var module = {
  someProp: hello,
  someMethod: function () {
    console.log(this.someProp);
  }
};

var bankAccount = {
  balance: 9000000,
  deposit: function (amount) {
    this.balance += amount;
  },
  withdraw: function (amount) {
    this.balance -= amount;
  }
};

bankAccount.deposit(20000);
bankAccount.withdraw(5000);

bankAccount.balance = 0; // .balance를 수정할 수 있게 노출되있다. (위험요소)
  
//1-2. IIFE (즉시실행함수), 정보의 노출을 판단하여 작성
var bankAccount = (function () {
  var balance = 0;

  return {
    deposit: amount => {
      balance += amount;
    },
    deposit1 : function(amount){

    },
    withdraw: amount => {
      balance -= amount;
    }
  };
})();

(function bankApp () {
  function createBankAccount (user, password) {
    var balance = 0;

    return {
      deposit: amount => {
        balance += amount;
      },
      withdraw: (amount, pw) => {
        if (password !== pw) {
          return;
        }

        balance -= amount;
      }
    }
  }

  var account1 = createBankAccount('ken', 123);
})();

//1-3. 싱글턴 패턴 (Singletons) : 생성을 하나로 제한한다.
var HTTPModule = null;

function createHTTPModule () {
  if (HTTPModule) {
    return HTTPModule;
  } else {
    HTTPModule = {
      get: url => {
        return $.get(url);
      },
      post: (url, data) => {
        return $.post(url, data);
      }
    };

    return HTTPModule;
  }
}

var HTTP = createHTTPModule();
  • 재사용 패턴
//Behavior Delegation 패턴

업데이트: