STUDY/디자인패턴

Flyweight 플라이웨이트 패턴

램플릿 2024. 7. 15. 11:12
// 플라이웨이트 (스크립터블 오브젝트)
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

[CreateAssetMenu(fileName = "FlyWeightData", menuName = "ScriptableSingletons/FlyWeightData")]
public class FlyWeightData : ScriptableSingleton<FlyWeightData>
{
    public int data = 10;
    public int data2 = 10;
    public int data3 = 10;
}
//플라이웨이트 사용 클래스

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FlyWeightPatternExample : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log(FlyWeightData.instance.data3);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
//플라이웨이트 사용 안할시
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NoFlyWeightData : MonoBehaviour
{
    public int data = 10;
    public int data2 = 10;
    public int data3 = 10;
    
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log(data);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

차이점 : 플라이웨이트를 사용하면 데이터를 한곳에서 관리할 수 있고, 인스턴스를 여러개 만들어도 데이터를 복사해서 사용하지 않아 메모리를 적게 소모할 수 있다.