JavaScript - ์ „๋žต ํŒจํ„ด ๐Ÿง 

7044 ๋‹จ์–ด tutorialwebdevjavascript
๋‚ด๋ถ€์— ์ผ€์ด์Šค๊ฐ€ ๋งŽ์€ ์—ฌ๋Ÿฌ if/else if ๋˜๋Š” switch ๋ฌธ์„ ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ์„ ํ”ผํ•˜๊ณ  ์‹ถ์Šต๋‹ˆ๊นŒ?

์ „๋žต ํŒจํ„ด์ด ์šฐ๋ฆฌ์—๊ฒŒ ๋„์›€์ด ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์‚ฌ์šฉ์ž๊ฐ€ ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ€์ž…ํ•  ์ˆ˜ ์žˆ๋Š” ์‚ฌ์šฉ ์‚ฌ๋ก€๊ฐ€ ์žˆ๋‹ค๊ณ  ์ƒ์ƒํ•ด ๋ณด์‹ญ์‹œ์˜ค.
  • ๊ตฌ๊ธ€ ์ธ์ฆ
  • ํŽ˜์ด์Šค๋ถ ์ธ์ฆ
  • ์–‘์‹ ์ œ์ถœ

  • ์šฐ๋ฆฌ๋Š” ์ด๊ฒƒ์„ ํ”ผํ•˜๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค:

    const AUTH_METHODS = {
      GOOGLE: 'GOOGLE',
      FACEBOOK: 'FACEBOOK',
      FORM_SUBMISSION: 'FORM_SUBMISSION'
    }
    
    const googleAuth = _ => {
      // ... Google auth code here
    }
    
    const facebookAuth = _ => {
      // ... Facebook Auth code here
    }
    
    const formSubmissionAuth = _ => {
      // ... Form submission code here
    }
    
    const handleAuthentication = method => {
      if (method === AUTH_METHODS.GOOGLE) {
        googleAuth()
      } else if (method === AUTH_METHODS.FACEBOOK) {
        facebookAuth()
      } else {
        formSubmissionAuth()
      }
    }
    


    ์ „๋žต ํŒจํ„ด์„ ์‚ฌ์šฉํ•˜์—ฌ ์ด๋ฅผ ์–ด๋–ป๊ฒŒ ๊ฐœ์„ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๊นŒ?

    const AUTH_METHODS = {
      GOOGLE: 'GOOGLE',
      FACEBOOK: 'FACEBOOK',
      FORM_SUBMISSION: 'FORM_SUBMISSION'
    }
    
    const googleAuth = _ => {
      // ... Google auth code here
    }
    
    const facebookAuth = _ => {
      // ... Facebook Auth code here
    }
    
    const formSubmissionAuth = _ => {
      // ... Form submission code here
    }
    
    const authenticationStrategy = method => ({
      [AUTH_METHODS.GOOGLE]: googleAuth,
      [AUTH_METHODS.FACEBOOK]: facebookAuth,
      [AUTH_METHODS.FORM_SUBMISSION]: formSubmissionAuth
    })[method]
    
    const strategy = authenticationStrategy(AUTH_METHODS.GOOGLE)
    strategy()
    


    ๊ทธ๋ฆฌ๊ณ  ์ผ๋ถ€ ์ „๋žต ํ•จ์ˆ˜์— ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์ „๋‹ฌํ•˜๋ ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

    const authenticationStrategy = method => ({
      [AUTH_METHODS.GOOGLE]: googleAuth,
      [AUTH_METHODS.FACEBOOK]: facebookAuth,
      [AUTH_METHODS.FORM_SUBMISSION]: () => formSubmissionAuth({ username: 'javascript', password: 'strategyPattern' })
    })[method]
    


    ์ „๋žต ํŒจํ„ด์€ ํ‚ค/๊ฐ’ ์Œ์ด ์žˆ๋Š” ๊ฐœ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ  "์‹คํ–‰"ํ•  ํ‚ค๋ฅผ ๊ฒฐ์ •ํ•˜๋Š” ๊ฒƒ์€ ๋งˆ์ง€๋ง‰์— [method]์ž…๋‹ˆ๋‹ค. ์ด๊ฒƒ์€ ์šฐ๋ฆฌ๊ฐ€ ์ „๋‹ฌํ•˜๋Š” ๊ฐ’์ด ๋ฌด์—‡์ด๋“  ๊ฐ„์— ํ•จ์ˆ˜์˜ ์ข…์†์„ฑ์ž…๋‹ˆ๋‹ค. ํ•ด๋‹น ๊ฐœ์ฒด ํ‚ค์— ๋งคํ•‘๋ฉ๋‹ˆ๋‹ค.

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