设计模式 -- 组合模式的一次运用实践
2017-06-08 10:58
375 查看
使用场景
在公司游戏项目中,有多种游戏模式,主要分为PVP和PVE。在PVE模式下面又细分为PVECloneBattle、PVEGuildBossBattle等等。在PVP模式下又分为AsyncPVP、FakePVP等。每种具体的游戏模式都有一套自己的初始化流程,之前是用的If else的方法暴力判断,然后调用各自的初始化函数。这段时间游戏开发任务较轻,决定重构这部分内容。经分析,可以使用组合模式来完成重构。具体代码如下:
using UnityEngine; using System.Collections; using System.Collections.Generic; public class NewBehaviourScript : MonoBehaviour { FightDataInitController controller = new FightDataInitController(); void Start() { controller.AddChild(new PVEMode()); controller.AddChild(new CloneMode()); controller.Init(); } } abstract class Mode { public abstract void _InitBefore(); public abstract void _InitCommon(); public abstract void _InitAfter(); public void Init() { _InitBefore(); _InitCommon(); _InitAfter(); } } class PVEMode : Mode { public override void _InitBefore() { Debug.Log("PVE模式的InitBefore"); } public override void _InitCommon() { Debug.Log("PVE模式的InitCommon"); } public override void _InitAfter() { Debug.Log("PVE模式的InitAfter"); } } class PVPMode : Mode { public override void _InitBefore() { Debug.Log("PVP模式的InitBefore"); } public override void _InitCommon() { Debug.Log("PVP模式的InitCommon"); } public override void _InitAfter() { Debug.Log("PVP模式的InitAfter"); } } class CloneMode : Mode { public override void _InitBefore() { Debug.Log("Clone模式的InitBefore"); } public override void _InitCommon() { Debug.Log("Clone模式的InitCommon"); } public override void _InitAfter() { Debug.Log("Clone模式的InitAfter"); } } class GuildBossMode : Mode { public override void _InitBefore() { Debug.Log("GuildBoss模式的InitBefore"); } public override void _InitCommon() { Debug.Log("GuildBoss模式的InitCommon"); } public override void _InitAfter() { Debug.Log("GuildBoss模式的InitAfter"); } } class FightDataInitController : Mode { private List<Mode> m_ChildList = new List<Mode>(); public void AddChild(Mode childMode) { m_ChildList.Add(childMode); } public override void _InitBefore() { for (int i = 0; i < m_ChildList.Count; i ++ ) { m_ChildList[i]._InitBefore(); } } public override void _InitCommon() { for (int i = 0; i < m_ChildList.Count; i++) { m_ChildList[i]._InitCommon(); } } public override void _InitAfter() { for (int i = 0; i < m_ChildList.Count; i++) 4000 { m_ChildList[i]._InitAfter(); } } }
每种具体模式都继承于基类Mode。在FightDataInitController中,根据实际情况,组合不同模式。
组合模式适用范围
组合模式是23种设计模式之一,适用于如下这种树形结构的程序。可以统一管理根和叶子节点。重构后,可以很好地扩展,如果有新的游戏模式需求,只用新些一个派生类,而不用改写原来代码。相关文章推荐
- 一次运用设计模式对现有系统进行重构的尝试(一)
- 一次重构导向设计模式的实践
- 如何掌握并在实践中自如运用设计模式
- 一次运用设计模式对现有系统进行重构的尝试(二)
- iOS应用开发中运用设计模式中的组合模式的实例解析
- 如何掌握并在实践中自如运用设计模式
- 如何掌握并在实践中自如运用设计模式
- 剖析设计模式编程中C#对于组合模式的运用
- 如何掌握并在实践中自如运用设计模式
- 设计模式3实践——运用 C# 中的 delegate 简化设计模式的实现
- 如何掌握并在实践中自如运用设计模式
- [Golang]设计模式实践:组合(Composite)
- 【学习笔记javascript设计模式与开发实践(组合模式)----10】
- 设计模式实践系列 (2) - 组合模式 ( Composite )
- 【学习笔记javascript设计模式与开发实践(组合模式)----10】
- Go语言设计模式实践:组合(Composite)
- 设计模式讲解与代码实践(九)——组合
- 如何掌握并在实践中自如运用设计模式
- 如何掌握并在实践中自如运用设计模式
- 如何掌握并在实践中自如运用设计模式 构架设计