游戏中的设计模式四(桥接模式)

写在前面

在游戏中的角色和武器,往往一个角色可以装换多种武器,武器也拥有诸多类型

当角色需要配备不同武器时候,需要修改角色类,使其配备另外的武器对象

这样造成对象与对象之间耦合性高,并且不容易扩展

使用桥接模式,将抽象与实现分离,使它们都可以独立地变化

案例分析

在各个帮派角色中,可以使用倚天剑和屠龙刀,当角色需要切换不同武器时候,就要大量的修改角色类来调用另外的武器


使用桥接模式,将抽象与实现分离


代码编写

角色基类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();
	}
}


输出结果如下图所示


这样当我们主角需要配备不同武器时候,只需要修改不同武器类即可

同时代码扩展性也强,比如当我们游戏中有另外一种武器时候不需要修改代码,只是在原来的基础上添加代码

总结

桥接模式用于把抽象化和实现化解耦,使得两者可以独立变化,即实体类的功能独立于接口实现类。这两种类型的类可被结构化而互不影响。


原文地址:blog.liujunliang.com.cn

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值