Observer Design Pattern
Observer Pattern
ํ ๊ฐ์ฒด์ ์ํ๊ฐ ๋ฐ๋๋ฉด, ๊ทธ ๊ฐ์ฒด๋ฅผ ์์กดํ๋ ๋ค๋ฅธ ๊ฐ์ฒด์ ์ฐ๋ฝ์ด ๊ฐ๊ณ ์๋์ผ๋ก ๋ด์ฉ์ด ๊ฐฑ์ ๋๋๋ก ํ๋ ํจํด์ผ๋ก OneToMany ์์กด์ฑ์ ์ ์ํ๋ค. ์ฌ๊ธฐ์ OneToMany ์์กด์ฑ์ด๋, ์ฃผ์ ๋ ์ํ๋ฅผ ์ ์ฅํ๊ณ ์ ์ดํ๋ค. ๋ฐ๋ผ์ ์ํ๊ฐ ๋ค์ด์๋ ๊ฐ์ฒด๋ ์ค๋ก์ง ํ๋์ด๋ค. ๋ฐ๋ฉด์ ๊ทธ ์ํ๋ฅผ ์์กดํ๋ Observer ๊ฐ์ฒด๋ ์ฌ๋ฌ๊ฐ์ด๋ค ๋ผ๋ ์๋ฏธ์ด๋ค.โฉโฉ
์ฃผ๋ก ํ๋ก ํธ์๋ ๊ด์ ์์, observer pattern์ ์ ์ํ ๊ณณ์ด ๋ง์ง๋ง ๋ฐฑ์๋์์๋ observer pattern์ผ๋ก ๊ตฌํํ๋ ์์ ์ผ์ด์ค๋ค์ด ๋ง๋ค. ์๋ฅผ ๋ค์ด, nodejs์ eventEmitter / logging / socket / distributed system / caching
observer pattern์ ์ฌ์ฉํ๋ ์ด์
- Subject์ Observer ๊ฐ ์๋ก ๋ ๋ฆฝ์ ์ผ๋ก ๋์จํ๊ฒ ๊ฒฐํฉ๋์ด Subject์ ๋ณํ๊ฐ ์์ด๋ Observer์๋ ์ํฅ์ ๋ฏธ์น์ง ์๋๋ค๋ ์ฅ์ ์ด ์๋ค.
- ์ฌ๋ฌ Observer๊ฐ ์กด์ฌํ๊ณ ์๋ ์ํฉ์์, ์๋ก์ด Observer๊ฐ ์ถ๊ฐ๋๋ค๋ฉด ๋จ์ํ Subject๊ฐ
๊ตฌ๋
๋ง ํด์ฃผ๋ฉด ๋๋ค. ๋ฐ๋๋ ๋ง์ฐฌ๊ฐ์ง์ด๋ค. - Observer pattern ์์๋ Subject ๋ง์ด ์ํ๋ฅผ ์ ์ฅํ๊ณ ์ ์ดํจ์ผ๋ก์จ, ๋ฆฌ์์ค๋ฅผ ํจ์จ์ ์ผ๋ก ๊ด๋ฆฌํ๊ณ ๋ฐ์ดํฐ๋ฅผ ์ ์ดํ ์ ์๋ ๊ณณ์ ํ๋์ด๋ฏ๋ก ๋ฐ์ดํฐ์ ์ผ๊ด์ฑ์ ์ ์งํ ์ ์๋ค.
- ๋น๋๊ธฐ ์์ ์ ๊ฐ์ํ๊ณ ์๋ค๊ฐ, ์๋ฆผ์ผ๋ก ์ ๋ฌํ๊ธฐ๋ง ํ๋ฉด ๋๋ค.
๋์จํ ๊ฒฐํฉ(loose coupling)
- ์ฃผ์ ๋ ์ต์ ๋ฒ๊ฐ ํน์ interface๋ฅผ ๊ตฌํํ๋ค๋ ์ฌ์ค๋ง ์๋ค.
- ์ต์ ๋ฒ๋ ์ธ์ ๋ ์ง ์ถ๊ฐ๋๊ฑฐ๋ ์ ๊ฑฐ๋ ์ ์๋ค.
- ์ฃผ์ ๋ ์ต์ ๋ฒ๋ฅผ ๋ค๋ฅธ ๊ณณ์์ ๋ค๋ฅธ ์ฉ๋๋ก ์ฌ์ฉํ๋ค๊ณ ํด๋ ๋ฌธ์ ๊ฐ ์๋ค. ์๋ํ๋ฉด ๋์จํ๊ฒ ๊ฒฐํฉ๋์ด ์๊ธฐ ๋๋ฌธ์ด๋ค.
๋์จํ ๊ฒฐํฉ์ ๊ฐ์ฒด ์ฌ์ด์ ์ํธ์์กด์ฑ์ ์ต์ํํจ์ผ๋ก์จ ๋ณ๊ฒฝ์ฌํญ์ด ์๊ฒจ๋ ๋ฌด๋ํ ์ฒ๋ฆฌํ ์ ์๋ ์ ์ฐํ ๊ฐ์ฒด์งํฅ ์์คํ ์ ๊ตฌ์ถํ๋ ๋ฐฉ๋ฒ์ด๋ค.
์์
์๋ฅผ ๋ค์ด NewPost๋ผ๋ class๊ฐ ์๋ค๊ณ ๊ฐ์ ํ์. ์ด class ๋ ์๋ก ๋ฐํ๋ ๊ฒ์๋ฌผ์ ๊ด๋ฆฌํ๋๋ฐ ์๋ก์ด ๊ฒ์๋ฌผ์ด ๋ฑ๋ก๋ ๋๋ง๋ค ์ฐ๋ฆฌ๋ ์นดํ ๊ณ ๋ฆฌ๋ณ ๊ฒ์๊ธ ์๋ฅผ ์ ๋ฐ์ดํธ / ์ผ๋ณ ํฌ์คํ ์ ์ ๋ฐ์ดํธ / ํด๋น ๊ฒ์๊ธ์ ์์ฑํ ์ ์ ๋ฅผ ํ๋ก์ํ๊ณ ์๋ ์ฌ๋๋ค์๊ฒ ๋๊ฐ ์๋ฆผ ์๋ฅผ ์ ๋ฐ์ดํธํด์ผ ํ๋ค๊ณ ํด๋ณด์.
๊ตฌํ๋ณด๋ค๋ ์ธํฐํ์ด์ค๋ผ๋ ๋์์ธ ์์น / ๋ฐ๋๋ ๋ถ๋ถ์ ์บก์ํํ๋ค๋ ๋์์ธ ์์น์ ์ด๊ธฐ๊ณ ๋์ถฉ ์ง๋ณด๋ฉด ๋ค์๊ณผ ๊ฐ์ ๊ฒ์ด๋ค.
|
|
์์ ๊ฐ์ด ๊ตฌ์ฑ์ ํ๊ฒ ๋๋ฉด, ์ถ๊ฐ์ ์ธ ํต๊ณ์ ๋ณด๋ฅผ ์ถ๊ฐํ๊ฑฐ๋ ์ญ์ ํ ์๊ฐ ์๋ค. ์๋ํ๋ฉด ์ด๋ฏธ newPosts๋ผ๋ ๊ฐ์ฒด์์ ๊ตฌํ๋์ด ์๊ธฐ ๋๋ฌธ์ด๋ค. ์ถ๊ฐ์ ์ผ๋ก updateํ๋ ํจ์๋ ์ถฉ๋ถํ ๋ฐ๋ ์ฌ์ง๊ฐ ์์ผ๋ฏ๋ก ์บก์ํ๋ฅผ ํด์ผํ ๊ฒ์ด๋ค.
|
|
์ ์ฒ๋ผ ๊ตฌ์ฑํ๊ฒ ๋๋ฉด, ์๋์ ๊ฐ์ด subject ๊ฐ observer๋ฅผ ๊ตฌ๋ ํ๊ณ ๋๋ ํด์งํ๋ ๊ฒ์ด ์ฉ์ดํ๋ค.
|
|