//抽象共享组件
public interface IFlyWeight {
bool CheckMaxValue(int val);
}//具体的共享组件
public class EnemyMaxFlyweight : IFlyWeight
{
private int maxHp = 999999;
public bool CheckMaxValue(int val)
{
if (val > maxHp) return false;
return true;
}
}using System.Collections.Generic;
//工厂类
public class FlyweightFactory {
private static FlyweightFactory _instance;
private Dictionary<string, IFlyWeight> dic = new Dictionary<string, IFlyWeight>();
private FlyweightFactory()
{
dic.Add("MaxEnemyHp", new EnemyMaxFlyweight());
}
public static FlyweightFactory Instance {
get {
if (_instance == null) _instance = new FlyweightFactory();
return _instance;
}
}
public IFlyWeight GetFlyWeight(string key)
{
if (dic.ContainsKey(key))
return dic[key];
return null;
}
}//测试使用
using UnityEngine;
public class testFlyweight : MonoBehaviour {
void Start () {
int enemyHp = 1000000;
bool isgo = FlyweightFactory.Instance.GetFlyWeight("MaxEnemyHp").CheckMaxValue(enemyHp);
if (!isgo) {
Debug.Log("生成的敌人生命值超过限制!");
}
}
}这里举的例子是关于一类敌人的生成的,假如这类敌人要不停生成,生命不限定,有最大生命值的限定,超过就让他等于最大生命值等,这个最大生命值是固定不变且可以在多个敌人生成器中共享的,所以把这个最大生命值提取出来作为共享元素,当然游戏中,很多的属性都是共享的,只要就只占用一份内存了。