Skip to content

Latest commit

ย 

History

History
83 lines (59 loc) ยท 2.68 KB

Design Pattern_Template Method.md

File metadata and controls

83 lines (59 loc) ยท 2.68 KB

๋””์ž์ธ ํŒจํ„ด _ Template Method Pattern


[๋””์ž์ธ ํŒจํ„ด ์˜ˆ]

  1. ํ…œํ”Œ๋ฆฟ ๋ฉ”์„œ๋“œ ํŒจํ„ด

    ํŠน์ • ํ™˜๊ฒฝ or ์ƒํ™ฉ์— ๋งž๊ฒŒ ํ™•์žฅ, ๋ณ€๊ฒฝํ•  ๋•Œ ์œ ์šฉํ•œ ํŒจํ„ด

    ์ถ”์ƒ ํด๋ž˜์Šค, ๊ตฌํ˜„ ํด๋ž˜์Šค ๋‘˜๋กœ ๊ตฌ๋ถ„.

    ์ถ”์ƒํด๋ž˜์Šค (Abstract Class) : ๋ฉ”์ธ์ด ๋˜๋Š” ๋กœ์ง ๋ถ€๋ถ„์€ ์ผ๋ฐ˜ ๋ฉ”์†Œ๋“œ๋กœ ์„ ์–ธํ•ด ๋‘ .

    ๊ตฌํ˜„ํด๋ž˜์Šค (Concrete Class) : ๋ฉ”์†Œ๋“œ๋ฅผ ์„ ์–ธ ํ›„ ํ˜ธ์ถœํ•˜๋Š” ๋ฐฉ์‹.

    • ์žฅ์ 
      • ๊ตฌํ˜„ ํด๋ž˜์Šค์—์„œ๋Š” ์ถ”์ƒ ํด๋ž˜์Šค์— ์„ ์–ธ๋œ ๋ฉ”์†Œ๋“œ๋งŒ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ, ํ•ต์‹ฌ ๋กœ์ง ๊ด€๋ฆฌ๊ฐ€ ์šฉ์ด
      • ๊ฐ์ฒด ์ถ”๊ฐ€ ๋ฐ ํ™•์žฅ ๊ฐ€๋Šฅ
    • ๋‹จ์ 
      • ์ถ”์ƒ ๋ฉ”์†Œ๋“œ๊ฐ€ ๋งŽ์•„์ง€๋ฉด, ํด๋ž˜์Šค ๊ด€๋ฆฌ๊ฐ€ ๋ณต์žกํ•จ.
    • ์„ค๋ช…

      1. HouseTemplate.java

      Template ์ถ”์ƒ ํด๋ž˜์Šค๋ฅผ ํ•˜๋‚˜ ์ƒ์„ฑ. (์˜ˆ, HouseTemplate)

      ์ด HouseTemplate์„ ์‚ฌ์šฉํ•  ๋•Œ๋Š”,

      "HouseTemplate houseType = new WoodenHouse()" ์ด๋Ÿฐ ์‹์œผ๋กœ ๋„ฃ์Œ.

      HouseTemplate ๋‚ด๋ถ€์— **buildHouse**๋ผ๋Š” ๋ณ€ํ•ด์„œ๋Š” ์•ˆ๋˜๋Š” ํ•ต์‹ฌ ๋กœ์ง์„ ๋งŒ๋“ค์–ด ๋†“์Œ. (์žฅ์  1)

      Template ํด๋ž˜์Šค ๋‚ด๋ถ€์˜ **ํ•ต์‹ฌ ๋กœ์ง ๋‚ด๋ถ€์˜ ํ•จ์ˆ˜**๋ฅผ ์ƒ์†ํ•˜๋Š” ํด๋ž˜์Šค๊ฐ€ ์ง์ ‘ ๊ตฌํ˜„ํ•˜๋„๋ก, abstract๋ฅผ ์ง€์ •ํ•ด ๋‘ .

      public abstract class HouseTemplate {
          
          // ์ด๋Ÿฐ ์‹์œผ๋กœ buildHouse๋ผ๋Š” ํ•จ์ˆ˜ (ํ•ต์‹ฌ ๋กœ์ง)์„ ์„ ์–ธํ•ด ๋‘ .
          public final void buildHouse() {
              buildFoundation();	// (1)
              buildPillars();		// (2)
              buildWalls();		// (3)
              buildWindows();		// (4)
              System.out.println("House is built.");
          }
          
          // buildFoundation(); ์ •์˜ ๋ถ€๋ถ„ (1)
          // buildWalls(); ์ •์˜ ๋ถ€๋ถ„		(2)
          
          // ์œ„์˜ ๋‘ ํ•จ์ˆ˜์™€๋Š” ๋‹ค๋ฅด๊ฒŒ ์ด ํด๋ž˜์Šค๋ฅผ ์ƒ์†๋ฐ›๋Š” ํด๋ž˜์Šค๊ฐ€ ๋ณ„๋„๋กœ ๊ตฌํ˜„ํ–ˆ์œผ๋ฉด ํ•˜๋Š” ๋ฉ”์†Œ๋“œ๋“ค์€ abstract๋กœ ์„ ์–ธํ•˜์—ฌ, ์ •์˜ํ•˜๋„๋ก ํ•จ
          public abstract void buildWalls();	// (3)
          public abstract void buildPillars();// (4)
          
      }
      1. WoodenHouse.java (GlassHouse.java๋„ ๊ฐ€๋Šฅ)

      HouseTemplate์„ ์ƒ์†๋ฐ›๋Š” ํด๋ž˜์Šค.

      Wooden์ด๋‚˜, Glass์— ๋”ฐ๋ผ์„œ buildHouse ๋‚ด๋ถ€์˜ ํ•ต์‹ฌ ๋กœ์ง์ด ๋ฐ”๋€” ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ,

      ์ด ๋ถ€๋ถ„์„ ๋ฐ˜๋“œ์‹œ ์„ ์–ธํ•˜๋„๋ก ์ง€์ •ํ•ด๋‘ .

      public class WoodenHouse extends HouseTemplate {
          @Override
          public void buildWalls() {
              System.out.println("Building Wooden Walls");
          }
          @Override
          public void buildPillars() {
              System.out.println("Building Pillars with Wood coating");
          }
      }