网站域名注册多少钱,wordpress标签链接,mysql8.0 wordpress,网站维护具体工作内容访问者模式 介绍
设计模式定义案例问题堆积在哪里访问模式访问模式是行为型设计模式 从对象中分类出算法 这些算法封装为对象#xff0c; 这样这些算法类很容易扩展#xff0c;添加新的算法类就可以了不同的VIP用户 在不同的节日 领取不同的礼物if else太多
解决办法小技巧…访问者模式 介绍
设计模式定义案例问题堆积在哪里访问模式访问模式是行为型设计模式 从对象中分类出算法 这些算法封装为对象 这样这些算法类很容易扩展添加新的算法类就可以了不同的VIP用户 在不同的节日 领取不同的礼物if else太多
解决办法小技巧枚举出不同的用户类有一个相同的基类 枚举出不同的节日类有一个相同的基类 节日访问者 被 不同VIP等级用户访问 根据不同的用户给出不同的礼物 if else。。。转为重载函数方式 函数重载类型1 函数重载类型2 ... 传入不同的数据类型触发不同的重置函数
类图 代码
PlayerVipBase public abstract class PlayerVipBase
{public string name;
}PlayerVipSun public class PlayerVipSun : PlayerVipBase
{public PlayerVipSun(){name VipSun; }
}PlayerVipMoon public class PlayerVipMoon : PlayerVipBase
{public PlayerVipMoon(){name VipMoon ; }
}PlayerVipStar public class PlayerVipStar : PlayerVipBase
{public PlayerVipStar(){name VipStar;}
} FestivalBase interface FestivalBase
{string GetGift(PlayerVipStar player);string GetGift(PlayerVipMoon player);string GetGift(PlayerVipSun player);
}Festival_YuanXiaoJie public class Festival_YuanXiaoJie : FestivalBase
{public string GetGift(PlayerVipStar player){return player.name 领取了元宵节礼物: 66个复活币;}public string GetGift(PlayerVipMoon player){return player.name 领取了元宵节礼物: 可爱汤圆时装;}public string GetGift(PlayerVipSun player){return player.name 领取了元宵节礼物: SSR汤圆宝宝;}
}Festival_GuoQingJie public class Festival_GuoQingJie : FestivalBase
{public string GetGift(PlayerVipStar player){return player.name 领取了国庆节礼物: 100R;}public string GetGift(PlayerVipMoon player){return player.name 领取了国庆节礼物: 2023国庆时装;}public string GetGift(PlayerVipSun player){return player.name 领取了国庆节礼物: SSR龙神;}
}
Festival_61 public class Festival_61 : FestivalBase
{public string GetGift(PlayerVipStar player){return player.name 领取了儿童节礼物: 100QB;}public string GetGift(PlayerVipMoon player){return player.name 领取了儿童节礼物: 61时装;}public string GetGift(PlayerVipSun player){return player.name 领取了儿童节礼物: SSR凤凰宝宝;}
}
测试代码
using UnityEngine;public class TestFWZ : MonoBehaviour
{void Start(){// 不同Vip 等级的玩家PlayerVipStar player1 new PlayerVipStar();PlayerVipMoon player2 new PlayerVipMoon();PlayerVipSun player3 new PlayerVipSun();// 六一儿童节Festival_61 liuYi new Festival_61();// 国庆节Festival_GuoQingJie GuoQingJie new Festival_GuoQingJie();// 元宵节Festival_YuanXiaoJie YuanXiaoJie new Festival_YuanXiaoJie();// 领取奖励61儿童节Debug.Log(liuYi.GetGift(player1));Debug.Log(liuYi.GetGift(player2));Debug.Log(liuYi.GetGift(player3));Debug.Log(------------------------);// 领取奖励国庆Debug.Log(GuoQingJie.GetGift(player1));Debug.Log(GuoQingJie.GetGift(player2));Debug.Log(GuoQingJie.GetGift(player3));Debug.Log(------------------------);// 领取奖励国庆Debug.Log(YuanXiaoJie.GetGift(player1));Debug.Log(YuanXiaoJie.GetGift(player2));Debug.Log(YuanXiaoJie.GetGift(player3));}
}结果 总结
访问者模式是拆分出了领奖行为 后封装为对象这个对象管理了礼物。
礼物管理员进一步拆分为 多个不同节日的礼物管理员
管理员可以自动识别玩家VIP等级 发送不同的礼物
这里小技巧“重载-获取礼物函数不同的玩家类型”