간단한 패턴이다.

leaf와 Composite 모두 같은 인터페이스를 상속받고,
구현은 leaf에서, 하며 composite에서는 재귀적으로 자신의 리스트 안에 있는 leaf에서 구현을 호출하게 한다.
using System;
using System.Collections.Generic;
using UnityEngine;
public interface IComponent
{
void Operation();
}
public class Composite : IComponent
{
private List<IComponent> components = new List<IComponent>();
public void Add(IComponent component)
{
components.Add(component);
}
public void Remove(IComponent component)
{
components.Remove(component);
}
public void Operation()
{
Debug.Log(this + " 호출");
foreach (IComponent component in components)
{
component.Operation();
}
}
}
public class Leaf : IComponent
{
public void Operation()
{
Debug.Log("Leaf 호출");
}
}
void Start()
{
Composite root = new Composite();
Composite branch = new Composite();
Leaf leaf1 = new Leaf();
Leaf leaf2 = new Leaf();
root.Add(branch);
branch.Add(leaf1);
branch.Add(leaf2);
root.Operation();
}
'개념공부' 카테고리의 다른 글
디자인 패턴 : 프록시 패턴 (Proxy Pattern) (0) | 2025.01.10 |
---|---|
디자인 패턴 : 파사드 패턴 (0) | 2025.01.09 |
디자인 패턴 : 중재자 패턴 (0) | 2025.01.08 |
디자인 패턴 : 연쇄 책임 패턴 (Chain Of Responsibility) (0) | 2025.01.08 |
디자인 패턴 : 빌더 패턴 (0) | 2025.01.08 |