游戏中的设计模式八(享元模式)

来源:互联网 发布:桌游手机软件 编辑:程序博客网 时间:2024/05/16 09:46

博客地址:blog.liujunliang.com.cn

写在前面

在创建一类游戏对象中,往往会有一些属性重复创建占用内存,为了减少创建对象的数量,以减少内存占用和提高性能

使用享元模式将一些共同的属性元素分离,比如一类游戏对象的ID、name、攻击力(这里简单设置几个共同属性)设置为享元数据


案例分析

享元类

using System.Collections;using System.Collections.Generic;using UnityEngine;public class Attribute{    public int ID { get; set; }    public string name { get; set; }    public float attack { get; set; }}

工厂类(享元模式一般和工厂模式一起使用)

是享元模式核心类,使用容器存储各个享元模块,因而享元模式和对象池有异曲同工之妙

using System.Collections;using System.Collections.Generic;using UnityEngine;public class AttributeFactory{    private static AttributeFactory _instance;    public static AttributeFactory GetInstance    {        get        {            if (_instance == null)            {                _instance = new AttributeFactory();            }            return _instance;                        }    }    private Dictionary<int, Attribute> flyWeightDict = new Dictionary<int, Attribute>();    public AttributeFactory()    {        flyWeightDict.Add(0, new Attribute() { ID = 0, name = "0", attack = 0 });        flyWeightDict.Add(1, new Attribute() { ID = 1, name = "1", attack = 1 });    }    public Attribute GetAttribute(int ID)    {        if (flyWeightDict.ContainsKey(ID))        {            return flyWeightDict[ID];        }        return null;    }}

测试类

using System.Collections;using System.Collections.Generic;using UnityEngine;public class FlyweightDesign : MonoBehaviour{    private void Start()    {        Attribute attribute = AttributeFactory.GetInstance.GetAttribute(0);        Debug.Log(attribute.name);    }}

模式分析

模式定义:采用一个共享来避免大量拥有相同对象的开销

模式优点:大幅度降低内存中对象的数量

模式缺点:使系统逻辑复杂化,违背了系统开闭原则,当有新的享元数据时,需要给工厂类中的容器添加新的享元模块


博客地址:blog.liujunliang.com.cn






原创粉丝点击