Design Pattern

Mediator Pattern

eddie0329 2020. 10. 23. 16:35
๋ฐ˜์‘ํ˜•

๐Ÿ“Œ ๋ชฉ์ฐจ

  • Introduction
  • What's Mediator Pattern?
  • Implementation
  • Conclusion
  • Reference

๐Ÿ“Œ Introduction

์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ ํฌ์ŠคํŒ…์—์„œ๋Š” ์ค‘์žฌ์ž ํŒจํ„ด์— ๋Œ€ํ•ด ๋ฐฐ์›Œ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

๐Ÿ“Œ What's Mediator Pattern?

์ค‘์žฌ์ž ํŒจํ„ด์œผ๋กœ Messenger Class๋ฅผ ๊ตฌํ˜„ ํ•ด๋ณผ ํ…๋ฐ์š”. ์ค‘์žฌ์ž ํŒจํ„ด์€ ๋‹ค์Œ ๋„ํ˜•๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

Message๋ฅผ ๊ฐ๊ฐ์˜ participants์—๊ฒŒ ๋ฟŒ๋ ค์ฃผ๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ์—ฌ๊ธฐ์—์„  ์ผ๋‹จ ๋‘๋ช…๋งŒ ๋“ฑ๋ก์„ ํ•˜๋Š” ๊ฒƒ์œผ๋กœ ๊ฐ€์ •์„ ํ•˜๊ณ  ์–ด๋–ป๊ฒŒ ๊ตฌํ˜„์ด ๋˜๋Š”์ง€๋ฅผ ๋ณด์—ฌ๋“œ๋ฆฌ๊ณ˜์Šต๋‹ˆ๋‹ค.

๐Ÿ“Œ Implementation

์ผ๋‹จ ์ค‘์žฌ์ž ํŒจํ„ด์œผ๋กœ ์“ด Messenger๋Š” ์ด๋ ‡๊ฒŒ ์ƒ๊ฒผ์Šต๋‹ˆ๋‹ค.

class Messenger {
  constructor() {
    this.participants = [];
  }
  register(participant) {
    this.participants.push(participant);
    return this;
  }
  deliver(sender, message) {
    this.participants.forEach((participant) => {
      if (participant !== sender) {
        console.log(`From ${sender}:\n Dear ${participant}.\n ${message}`);
      }
    });
    return this;
  }
}

์ฒ˜์Œ๋จผ์ € participant๋ฅผ ๋“ฑ๋ก์„ ํ•˜๊ณ  ๊ทธ๋’ค์— participant์—๊ฒŒ ๋ฉ”์„ธ์ง€๋ฅผ ๋ฐ›์•„ ๋ณด๋‚ธ ์‚ฌ๋žŒ์„ ์ œ์™ธํ•œ ๋ชจ๋“ ์ด์—๊ฒŒ messege๊ฐ€ ๊ฐ€๋Š” ๊ตฌ์กฐ์ž…๋‹ˆ๋‹ค.

const EDDIE = "eddie";
const CLARIE = "claire";

const messenger = new Messenger();
messenger.register(EDDIE);
messenger.register(CLARIE);
messenger.deliver(EDDIE, "Whut ssup");
//From eddie:
//  Dear claire.
//  Whut ssup

๐Ÿ“Œ Conclusion

์ค‘์žฌ์ž ํŒจํ„ด์€ ์–ผํ• ์˜ต์ €๋ฒ„ ํŒจํ„ด์ด๋ž‘ ๋งค์šฐ ์œ ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๋‘ ๋””์ž์ธ ํŒจํ„ด์˜ ๊ฐ€์žฅ ํฐ ์ฐจ์ด์ ์€ ์ค‘์•™์—์„œ ์ปจํŠธ๋กค ํ•˜๋Š” ์—ญํ• ์ด ์žˆ๋Š”๊ฐ€ ์—†๋Š”๊ฐ€์— ๋”ฐ๋ผ ๋‹ค๋ฆ…๋‹ˆ๋‹ค. ์ค‘์žฌ์ž ํŒจํ„ด์ด ๋งŽ์ด ์‚ฌ์šฉํ•˜๋Š” ๊ณณ์€ ์ฑ„ํŒ…, ์ž์› ๋ถ„๋ฐฐ๊ธฐ, ๊ฐ€๊ณ„๋ถ€ ๊ฐ™์€ ๊ฒƒ์— ๋งŽ์ด ์‚ฌ์šฉ๋œ๋‹ค๊ณ  ํ•˜๋„ค์š”. ๊ทธ๋Ÿผ ๋‹ค์Œ์— ๋˜๋ณด์•„์š” ~~

๐Ÿ“Œ Reference

๋ฐ˜์‘ํ˜•