享元模式

自作多情 提交于 2020-02-05 04:31:49
using UnityEngine;
public class ConcreteFlyWeight : FlyWeight
{
    public ConcreteFlyWeight(string name):base(name)
    {
    }
    public override void Operation()
    {
        Debug.Log("执行" + Name);
    }
}
using UnityEngine;
public abstract class FlyWeight
{
    public string Name;
    public FlyWeight(string name)
    {
        Name = name;
    }
    public abstract void Operation();
}
using System.Collections.Generic;
using UnityEngine;
public class FlyWeightFactory
{
    public Dictionary<string, FlyWeight> flyweightDic; //key 是共享组件的名称
    public FlyWeightFactory()
    {
        flyweightDic = new Dictionary<string, FlyWeight>();
    }
    //获得共享组件
    public FlyWeight GetFlyWeight(string key,string name=null)  //根据key获得一个共享组件,如果没有,就创建这个组件,加入到共享组件列表中
    {
        flyweightDic.TryGetValue(key,out FlyWeight res);
        if(res==null)
        {
            res = new ConcreteFlyWeight(name);
            flyweightDic[key] = res;
        }
        return res;
    }
    //获得非共享组件
    public UnsharedConcreteFlyWeight GetUnShared(string name)
    {
        return new UnsharedConcreteFlyWeight(name);
    }
    //获得包含共享组件的非共享组件
    public UnsharedConcreteFlyWeight GetUnSharedHasShared(string name,string key,string sharedName=null)
    {
        FlyWeight fw = GetFlyWeight(key, sharedName);
        UnsharedConcreteFlyWeight res = new UnsharedConcreteFlyWeight(name);
        res.SetFlyWeight(fw);
        return res;
    }
}
using System.Collections.Generic;
using UnityEngine;
public class UnsharedConcreteFlyWeight //不适用继承的方式,利用组合声明了一个可以指向共享组件的引用
{
    public FlyWeight flyWeight=null;
    public string Name;
    public UnsharedConcreteFlyWeight(string name)
    {
        Name = name;
        Debug.Log("创建非共享组件:" + name);
    }
    //设置共享组件
    public void SetFlyWeight(FlyWeight fw)
    {
        this.flyWeight = fw;
    }
    public void Operation()
    {
        Debug.Log($"执行{Name}--{flyWeight?.Name}");
    }
}
测试
            //共享单元c1只创建了一份。
            FlyWeightFactory factor = new FlyWeightFactory();
            FlyWeight c1 = factor.GetFlyWeight("c1", "共享单元1");
            FlyWeight c2 = factor.GetFlyWeight("c2","共享单元2");
            c1.Operation();
            c2.Operation();
            UnsharedConcreteFlyWeight u1 = factor.GetUnShared("非共享单元");
            u1.flyWeight = c1;
            u1.Operation();
            UnsharedConcreteFlyWeight u2 = factor.GetUnSharedHasShared("非共享单元2","c1");
            u2.Operation();

在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!