Unity中的享元模式

1、建立角色基本属性类。

namespace DesignMode
{
    public class CharacterBaseAttr
    {
        protected string mName;
        protected int mMaxHP;
        protected string mIconSprite;

        public string Name
        {
            get { return mName; }
        }

        public int MaxHP
        {
            get { return mMaxHP; }
        }

        public string IconSprite
        {
            get { return mIconSprite; }
        }

        public CharacterBaseAttr(string name, int maxHp, string iconSprite)
        {
            this.mName = name;
            mMaxHP = maxHp;
            this.mIconSprite = iconSprite;
        }
    }
}

2、建立角色抽象类。

namespace DesignMode
{
    public abstract class ICharacter
    {
        public CharacterBaseAttr mBaseAttr;

        public ICharacter()
        {
            BaseAttrFactory.Instance.characterBaseAttrDic.TryGetValue(this.GetType(), out mBaseAttr);
        }
    }
}

3、建立角色实体类。

namespace DesignMode
{
    public class SoldierCaptain:ICharacter
    {
    }
}
namespace DesignMode
{
    public class SoldierRookie:ICharacter
    {
    }
}
namespace DesignMode
{
    public class SoldierSergeant:ICharacter
    {
    }
}

4、建立属性工厂类。

using System;
using System.Collections.Generic;

namespace DesignMode
{
    public class BaseAttrFactory
    {
        private static BaseAttrFactory mInstance=new BaseAttrFactory();

        private BaseAttrFactory()
        {
            Init();
        }
        
        public static BaseAttrFactory Instance
        {
            get { return mInstance; }
        }

        public Dictionary characterBaseAttrDic;
        
        public void Init()
        {
            characterBaseAttrDic=new Dictionary();
            characterBaseAttrDic.Add(typeof(SoldierCaptain),new CharacterBaseAttr("上尉士兵", 100,  "CaptainIcon"));
            characterBaseAttrDic.Add(typeof(SoldierSergeant),new CharacterBaseAttr("中尉士兵", 80,  "SergeantIcon"));
            characterBaseAttrDic.Add(typeof(SoldierRookie),new CharacterBaseAttr("新手士兵", 60,  "RookieIcon"));
        }
    }
}

PS:享元模式是把对象的共同属性提炼出来,共同引用即可。优点是可以节省内存资源。缺点是代码复杂。

你可能感兴趣的:(设计模式)