๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“šAlgorithm ------------/๊ฐœ๋…์ •๋ฆฌ

Composite Pattern

์š”์ฆ˜ ์ Š์€์ด๋“ค์€ ๋ณธ๋””๋กœ ์ƒ์ถ•ํ•œ๋‹ค

 

์กฐ๊ธˆ ์˜ˆ์ „์— ๊ณต๋ถ€ํ–ˆ๋˜ ๋””์ž์ธ ํŒจํ„ด์ธ๋ฐ, ๋‹ค์‹œ ๋ณต์Šตํ•˜๋ฉด์„œ ์ •๋ฆฌํ•ด๋ณด์•˜๋‹ค

๋””์ž์ธ ํŒจํ„ด๋„ ์ฐพ์•„๋ณด๋ฉฐ ๊ฐœ๋ฐœํ–ˆ๋˜ ์—ด์ • ์–ด๋””๊ฐ”๋‹ˆ ๐Ÿฅน


 

Composite ๋œป

OOP์—์„œ ์ปดํฌ์ง€ํŠธ๋Š” ํ•˜๋‚˜ ์ด์ƒ์˜ ์œ ์‚ฌํ•œ ๊ฐ์ฒด๋ฅผ ๊ตฌ์„ฑ์œผ๋กœ ์„ค๊ณ„๋œ ๊ฐ์ฒด๋กœ ๋ชจ๋‘ ์œ ์‚ฌํ•œ ๊ธฐ๋Šฅ์„ ๊ฐ€์ง

๊ฐ์ฒด ๊ทธ๋ฃน์„ ์กฐ์ž‘ํ•˜๋Š” ๊ฒƒ ์ฒ˜๋Ÿผ ๋‹จ์ผ ๊ฐ์ฒด๋ฅผ ์กฐ์ž‘ํ•  ์ˆ˜ ์žˆ์Œ

 

Composite Pattern

ํด๋ผ์ด์–ธํŠธ๊ฐ€ ๋ณตํ•ฉ ๊ฐ์ฒด/๋‹จ์ผ ๊ฐ์ฒด๋ฅผ ๋™์ผํ•˜๊ฒŒ ์ทจ๊ธ‰ํ•˜๋Š” ๊ฒƒ์„ ๋ชฉ์ ์œผ๋กœ ํ•จ

ํŠธ๋ฆฌ ๊ตฌ์กฐ๋กœ ์ž‘์„ฑ, ์ „์ฒด-๋ถ€๋ถ„ ๊ด€๊ณ„ ํ‘œํ˜„

  • ํŠธ๋ฆฌ๊ตฌ์กฐ๋ฅผ ๋‹ค๋ฃฐ ๋•Œ, ๊ฐœ๋ฐœ์ž๋Š” ๋ฆฌํ”„๋…ธ๋“œ์™€ ๋ธŒ๋žœ์น˜ ๊ตฌ๋ณ„ํ•ด์•ผํ•จ
  • ๋ณต์žกํ•˜๊ฒŒ ๋งŒ๋“ค์ง€ ์•Š๊ธฐ → ์ธํ„ฐํŽ˜์ด์Šค ํ™œ์šฉํ•ด์„œ ์ž‘์„ฑํ•œ๋‹ค๋˜๊ฐ€

  • Client ํด๋ž˜์Šค๋Š” Leaf์™€ Composite ํด๋ž˜์Šค์— ์ง์ ‘ ์ฐธ์กฐ ํ•˜์ง€ ๋งˆ์„ธ์šฅ ๐Ÿ™…‍โ™€๏ธ๐Ÿ™…‍โ™€๏ธ
  • ์ธํ„ฐํŽ˜์ด์Šค์ธ Component๋งŒ ์ฐธ์กฐํ•˜๊ธฐ
  • Leaf๋Š” Component ์ธํ„ฐํŽ˜์ด์Šค ๊ตฌํ˜„
  • Composite ๋Š” Component ๊ฐ์ฒด ์ž์‹๋“ค์„ ์œ ์ง€ํ•˜๊ณ , operation() ๊ฐ™์€ ์š”์ฒญ์„ ํ†ตํ•ด ์ž์‹๋“ค์—๊ฒŒ ์ „๋‹ฌ

์ •๋ฆฌํ•˜์ž๋ฉด

  • Leaf: Component ์ธํ„ฐํŽ˜์ด์Šค ๊ตฌํ˜„, ๊ตฌ์ฒด ํด๋ž˜์Šค
  • Component: ๋ชจ๋“  component๋ฅผ ์œ„ํ•œ ์ถ”์ƒํ™” ๊ฐœ๋…, ์ธํ„ฐํŽ˜์ด์Šค
  • Composite: Component ์ธํ„ฐํŽ˜์ด์Šค ๊ตฌํ˜„, ๊ตฌํ˜„๋˜๋Š” leaf/composite ๋“ค์„ ๊ฐ€์ง€๊ณ  ๊ด€๋ฆฌํ•˜๋Š” ๋ฉ”์†Œ๋“œ ๊ตฌํ˜„.
    • ์ธํ„ฐํŽ˜์ด์Šค์— ์ž‘์„ฑ๋œ ๋ฉ”์†Œ๋“œ๋Š” ์ž์‹์—๊ฒŒ ์œ„์ž„ํ•˜๋Š” ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์คŒ

 

๊ทธ๋Ÿผ ์ด๋ ‡๊ฒŒ ๊ตฌํ˜„ ๊ฐ€๋Šฅ

Client๋Š” → Coposite1์—๋งŒ ์š”์ฒญ์„ ๋ณด๋‚ด๋ฉด ๋‹ค ์•Œ์•„์„œ ์ฃผ๋ฃจ๋ฃฉ ๋˜๋Š” ํ˜•ํƒœ

Component ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•œ ๊ฐ์ฒด๋“ค์€ ์ž์‹ ์˜ ๋ชจ๋“  ์ž์‹ ์š”์†Œ์—๊ฒŒ ์ „๋‹ฌ

 

๊ทธ๋Ÿผ ์ด๊ฑธ ๋ญ์—๋‹ค๊ฐ€ ์“ฐ๋ƒ๋ฉด

 

public class ImportCommand : CompositeCommand
{
    public ImportInvoicesCommand()
    {
        AddChild(new PlayVideoCommand());
        AddChild(new InsertToDatabaseCommand());
        AddChild(new RequestToCameraCommand());
    }
}

 

์ด๋Ÿฐ ์‹์œผ๋กœ ํด๋ผ์ด์–ธํŠธ์—์„œ ์ˆ˜ํ–‰ํ•  ์ž‘์—…๋“ค์„ ๋“ฑ๋ก์„ ํ•ด ๋†“๊ณ 

 

public void ImportInvoices()
{
    var command = new ImportInvoicesCommand();
        
    command.Execute();
}

 

Execute() ํ•จ์ˆ˜๋งŒ ํ˜ธ์ถœํ•ด์ฃผ๋ฉด, ์œ„์—์„œ AddChild๋กœ ๋“ฑ๋กํ•ด์ค€ ์ž‘์—…๋“ค์ด ์‹คํ–‰๋˜๋„๋ก ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค

๋น„์Šทํ•œ ์ž‘์—…์ธ๋ฐ ์—ฌ๋Ÿฌ ๊ฑด ์ง„ํ–‰ํ•  ๋•Œ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹์€ ๋“ฏ ํ•˜๋‹ค.