您的位置:首页 > 其它

设计模式 -- 组合模式的一次运用实践

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种设计模式之一,适用于如下这种树形结构的程序。可以统一管理根和叶子节点。重构后,可以很好地扩展,如果有新的游戏模式需求,只用新些一个派生类,而不用改写原来代码。

 
                                                    


    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: