[TIL] Design Patterns Structural Pattern (구조 패턴), Flyweight Pattern

Dreamer·2024년 10월 2일

1. 오늘 주제

오늘도 특별하게 다룰 주제가 없어 Design PatternsFlyweight Pattern에 대해 이야기 하려고 한다.
Flyweight PatternStructural Pattern으로 메모리 낭비를 방지하고 동일한 데이터를 공유하는 방식으로 생성 비용을 줄일 수 있는 패턴이다.
특히 많은 객체가 동일하거나 비슷한 데이터를 가지고 있을 때 유용하다. 유니티에서 사용 되는 곳은 ScriptableObject가 대표적으로 Flyweight Pattern 방식으로 구현 되어 있다. 일련의 ScriptableObject안에서 정의된 데이터를 다른 Object에서 사용하는 경우 원본 데이터는 그대로 가지고 있고 실제 객체에서는 참조하는 방식으로 사용한다.

2. Flyweight Pattern 사용하기

Flyweight Pattern 예시로는 여러가지 방법이 있지만, 다음과 같은 방식으로 사용할 수 있다.

// Flyweight 클래스 (공유할 객체)
public class Tree
{
    private string _type; // 내부 상태 (공유되는 나무 종류)

    public Tree(string type)
    {
        _type = type;
    }

    public void Display(int x, int y)
    {
        Console.WriteLine($"나무 종류: {_type}, 위치: ({x}, {y})");
    }
}

// FlyweightFactory 클래스
public class TreeFactory
{
    private Dictionary<string, Tree> _trees = new Dictionary<string, Tree>();

    public Tree GetTree(string type)
    {
        if (!_trees.ContainsKey(type))
        {
            // 새로운 나무 객체 생성 및 저장
            Tree newTree = new Tree(type);
            _trees[type] = newTree;
        }
        return _trees[type];
    }

    public int GetTreeCount()
    {
        return _trees.Count;
    }
}

// Client 코드
class Program
{
    static void Main(string[] args)
    {
        TreeFactory treeFactory = new TreeFactory();

        // 동일한 종류의 나무를 여러 위치에 그리기
        Tree oakTree = treeFactory.GetTree("참나무");
        oakTree.Display(10, 20);

        Tree pineTree = treeFactory.GetTree("소나무");
        pineTree.Display(30, 40);

        Tree anotherOakTree = treeFactory.GetTree("참나무");
        anotherOakTree.Display(50, 60);

        // 생성된 나무 객체 수 확인 (Flyweight 객체 공유 확인)
        Console.WriteLine($"생성된 나무 객체 수: {treeFactory.GetTreeCount()}");
    }
}

지금처럼 예시코드를 생각해보면, 유니티 개발할때 Flyweight Pattern 구조로 DataManager를 설계하는데 ScriptableObject를 사용한다면 굳이 직접 설계해서 할 필요는 없다.

하지만 내부 상태는 공유되어 메모리 사용량을 줄이고, 외부 상태는 개별적으로 처리하여 유연성을 제공하기 때문에 많은 데이터를 처리하는데에는 안 쓸이유가 없다.

역시나 Flyweight Pattern 을 사용하면 장점으로는

  • 메모리 절약: 동일한 객체를 공유함으로써 메모리 사용량을 줄일 수 있다.
  • 성능 향상: 객체 생성 비용을 절감하고, 불필요한 객체 생성이 줄어들어 성능이 향상된다.
profile
새로운 시작

0개의 댓글