游戏中的设计模式八(享元模式)
来源:互联网 发布:桌游手机软件 编辑:程序博客网 时间: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
阅读全文
1 0
- 游戏中的设计模式八(享元模式)
- 游戏中的设计模式:享元模式
- 设计模式在游戏中的应用--外观模式(八)
- 结构型:设计模式之享元模式(八)
- 深入浅出设计模式(八):10.合成模式(Composite) 11.享元模式(Flyweight)
- 设计模式学习笔记八:享元模式
- 设计模式(享元模式)
- c++设计模式(享元模式)
- 设计模式:享元模式(Flyweight)
- 设计模式:享元模式(Flyweight)
- 设计模式(14)-享元模式
- 设计模式:享元模式(Flyweight)
- 设计模式-享元模式(Flyweight)
- 设计模式(11)------享元模式
- 设计模式(十二)享元模式
- 设计模式(十二)享元模式
- 设计模式(11)-享元模式
- 设计模式(11)--享元模式
- 读取txt文件然后录入数据库(批处理)
- js页面上的excel导出
- 修改easyui window的title属性
- 欢迎使用CSDN-markdown编辑器
- 最全的常用正则表达式大全——包括校验数字、字符、一些特殊的需求等等
- 游戏中的设计模式八(享元模式)
- ruby 安装
- 线程Thread与Runnable接口
- 用户在线状态维护
- Lightoj1156【二分+贪心】
- 配置keepalived ping不通 解决办法
- Eslint 配置及规则说明
- 对卡尔曼滤波的理解
- SQL