享元模式

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();

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JustEasyCode

谢谢您

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值