写在前面
在游戏中的角色和武器,往往一个角色可以装换多种武器,武器也拥有诸多类型
当角色需要配备不同武器时候,需要修改角色类,使其配备另外的武器对象
这样造成对象与对象之间耦合性高,并且不容易扩展
使用桥接模式,将抽象与实现分离,使它们都可以独立地变化
案例分析
在各个帮派角色中,可以使用倚天剑和屠龙刀,当角色需要切换不同武器时候,就要大量的修改角色类来调用另外的武器
使用桥接模式,将抽象与实现分离
代码编写
角色基类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();
}
}
输出结果如下图所示
这样当我们主角需要配备不同武器时候,只需要修改不同武器类即可
同时代码扩展性也强,比如当我们游戏中有另外一种武器时候不需要修改代码,只是在原来的基础上添加代码
总结
桥接模式用于把抽象化和实现化解耦,使得两者可以独立变化,即实体类的功能独立于接口实现类。这两种类型的类可被结构化而互不影响。