寫在前面
在遊戲中的角色和武器,往往一個角色可以裝換多種武器,武器也擁有諸多類型
當角色需要配備不同武器時候,需要修改角色類,使其配備另外的武器對象
這樣造成對象與對象之間耦合性高,並且不容易擴展
使用橋接模式,將抽象與實現分離,使它們都可以獨立地變化
案例分析
在各個幫派角色中,可以使用倚天劍和屠龍刀,當角色需要切換不同武器時候,就要大量的修改角色類來調用另外的武器
使用橋接模式,將抽象與實現分離
代碼編寫
角色基類ICharacter
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ICharacter
{
public IWeapon weapon;
public string name;
public ICharacter(IWeapon weapon)
{
this.weapon = weapon;
}
public virtual void Use()
{
weapon.Start(this.name);
}
}
丐幫
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GBCharacter : ICharacter
{
public GBCharacter(IWeapon weapon) : base(weapon)
{
this.name = "GB";
}
}
武當
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WDCharacter : ICharacter
{
public WDCharacter(IWeapon weapon) : base(weapon)
{
this.name = "WD";
}
}
峨眉
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EMCharacter : ICharacter
{
public EMCharacter(IWeapon weapon) : base(weapon)
{
this.name = "EM";
}
}
武器基類
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class IWeapon
{
public string name;
//開始使用武器
public abstract void Start(string name);
}
屠龍刀
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TLDWeapon : IWeapon
{
public TLDWeapon()
{
this.name = "屠龍刀";
}
public override void Start(string name)
{
Debug.Log(name + "將武器切換爲" + this.name);
}
}
倚天劍
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YTJWeapon : IWeapon
{
public YTJWeapon()
{
this.name = "倚天劍";
}
public override void Start(string name)
{
Debug.Log(name + "將武器切換爲:" + this.name);
}
}
創建一個腳本繼承自Monobehavior
using UnityEngine;
class GameContext : MonoBehaviour
{
private void Start()
{
//SceneStateManager.GetInstacne.SetSceneState(new StartSceneState());
IWeapon ytjWeapon = new YTJWeapon();
IWeapon tldWeapon = new TLDWeapon();
ICharacter gb = new GBCharacter(ytjWeapon);
gb.Use();
ICharacter wd = new WDCharacter(tldWeapon);
wd.Use();
ICharacter em = new EMCharacter(ytjWeapon);
em.Use();
}
}
輸出結果如下圖所示
這樣當我們主角需要配備不同武器時候,只需要修改不同武器類即可
同時代碼擴展性也強,比如當我們遊戲中有另外一種武器時候不需要修改代碼,只是在原來的基礎上添加代碼
總結
橋接模式用於把抽象化和實現化解耦,使得兩者可以獨立變化,即實體類的功能獨立於接口實現類。這兩種類型的類可被結構化而互不影響。