Design Patterns with Javascript

4086 ๋‹จ์–ด Design PatternDesign Pattern

Design patterns makes code short, less bugs, maintainable, re-usable and scalable

์œ„ ์žฅ์ ์—๋„ ๋ถˆ๊ตฌํ•˜๊ณ  ์ฃผ์˜ํ•ด์„œ ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ๋ฉด ์œ„ ์žฅ์ ์ด ์ „๋ถ€ ๋ฐ˜๋Œ€๊ฐ€ ๋˜์–ด๋ฒ„๋ฆด ์ˆ˜ ์žˆ๋‹ค. ๊ฐ ํŒจํ„ด์— ๋Œ€ํ•œ ํŠน์„ฑ์„ ์ •ํ™•ํžˆ ํŒŒ์•…ํ•˜๊ณ  ์ ์ ˆํ•œ ๊ณณ์— ํ™œ์šฉ ํ•  ์ค„ ์•Œ์•„์•ผ ๋””์ž์ธ ํŒจํ„ด์„ ์‚ฌ์šฉํ•จ์œผ๋กœ ์ธํ•œ ์žฅ์ ์„ ๊ทน๋Œ€ํ™” ํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ๋””์ž์ธ ํŒจํ„ด๋งŒ์„ ์œ„ํ•œ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋Š”๊ฒƒ์„ ์กฐ์‹ฌํ•˜์ž.

Keep it simple and stupid ์œˆ์น™์„ ์ƒ๊ธฐํ•˜๋ฉด์„œ ๋””์ž์ธ ํŒจํ„ด์„ ํ™œ์šฉํ•˜์ž.

Null object pattern

Null safety ๋ฅผ ์œ„ํ•œ ํŒจํ„ด. ํ•จ์ˆ˜๋‚˜ ๋ฉ”์†Œ๋“œ์—์„œ ๋ฆฌํ„ดํ•˜๋Š” ๊ฐ์ฒด๊ฐ€ nullable ํ•  ๊ฒฝ์šฐ null ๋Œ€์‹  null object ๋ฅผ ๋ฐ˜ํ™˜ํ•˜์—ฌ runtime error ์„ ๋ฐฉ์ง€ํ•˜๊ณ  ์ฝ”๋“œ๋ฅผ ๊น”๋”ํ•˜๊ฒŒ ์ž‘์„ฑํ•˜์ž.

Builder Pattern

Builder ํด๋ž˜์Šค๋ฅผ ์ž‘์„ฑํ•˜๊ฑฐ๋‚˜ ์ƒ์„ฑ์ž์—์„œ optional ํŒŒ๋ผ๋ฏธํ„ฐ๋Š” ๊ฐ์ฒด๋กœ ๋ฐ›๊ณ , default ๊ฐ’์„ ํ™œ์šฉํ•˜์—ฌ ์ฝ”๋“œ๋ฅผ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ๋งŒ๋“ค์ž.

e.g)

class User {
	constructor(name, { age, address = 'seoul', email} = {}) {
		this.name = name
		this.age = age
		this.address = address
		this.email = email
	}
}

const user = new User('Sam', {age: 30, email: 'hellosam1332@gmail.com'})

console.log(user) // User {name: "Sam", age: 30, address: "seoul", email: "hellosam1332@gmail.com"}

Facade pattern

The idea of the facade pattern is to create your own API that hides away complex or repetitive code so that you are left with a clean and easy to use API. The benefits of this is not only clean code that is easy and fun to work with, but your code is also much easier to refactor when the complex code behind your facade needs to change.

Command Pattern

The idea of the command pattern is to create an abstraction between the operations an object can do, its commands, and the actual commands themselves. This makes it really easy to combine together or chain different commands without having to change the code. The program can dynamically chain and combine these actions. The best part is since each command is its own object you can easily implement and undo function for each command and make a set of undo-able actions.

Reference

https://www.youtube.com/watch?v=BWprw8UHIzA&list=PLZlA0Gpn_vH_CthENcPCM0Dww6a5XYC7f

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ