Unity装饰器设计模式

装饰器设计模式(Decorator Pattern)是一种**在不修改原有类代码的前提下,给对象"动态增加功能"的结构型设计模式。

你可以把它理解成:给对象穿衣服 ------人不变,但穿得越多,功能越多。
他是一种在不修改原有类、不通过继承爆炸的前提下,给对象动态叠加功能 的结构型设计模式。它强调的是 "组合优于继承" ------功能是层层包裹,而不是写死在类里。

1.基础代码

这里方便展示直接放到一个脚本里面了,重点是MessageDecorator 这个类,他起到了承上启下的作用,让继承了装饰者基类的类可以获取到上一个消息数据并且提供抽象方法让后面的装饰者可以继续添加功能。

它起到的是:

  • 向上:保存并调用"上一个消息"

  • 向下:为所有装饰器提供统一扩展入口。

cs 复制代码
using UnityEngine;

// 攻击消息接口
public interface IMessage
{
    string GetMessage();
}

// 基础消息类
public class SimpleMessage : IMessage
{
    public string GetMessage()
    {
        return "攻击";
    }
}

// 装饰器基类
public abstract class MessageDecorator : IMessage
{
    //持有上一条信息的引用
    protected IMessage decoratedMessage;

    protected MessageDecorator(IMessage message)
    {
        decoratedMessage = message;
    }

    public abstract string GetMessage();
}

// 具体装饰器:特效装饰器
public class EffectDecorator : MessageDecorator
{
    //使用父类构造函数
    public EffectDecorator(IMessage message) : base(message) { }

    public override string GetMessage()
    {
        //获取上一条消息并添加效果
        return decoratedMessage.GetMessage() + "+特效";
    }
}

// 具体装饰器:音效装饰器
public class SoundDecorator : MessageDecorator
{
    public SoundDecorator(IMessage message) : base(message) { }

    public override string GetMessage()
    {
        //获取上一条消息并添加效果
        return decoratedMessage.GetMessage() + "+音效";
    }
}

2.使用

cs 复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TextPlayer : MonoBehaviour
{
    void Start()
    {
        IMessage msg = new SimpleMessage();
        msg = new EffectDecorator(msg);
        msg = new SoundDecorator(msg);

        Debug.Log(msg.GetMessage());
    }
}

3.运行

4.添加新的装饰器

5.运行

总结:

装饰器模式的核心思想是"组合而非继承",它通过一层层包装对象,在不破坏原有逻辑的前提下动态叠加功能。

在游戏开发中,这种模式非常适合处理攻击效果、伤害信息、特效与音效叠加等需要灵活组合的场景,既能降低耦合,又能让系统在后期扩展时保持清晰和可维护。

相关推荐
weixin_424294672 天前
Unity 调用Steamworks API 的 SteamUserStats.RequestCurrentStats()报错
unity·游戏引擎·steamwork
HoFunGames2 天前
Unity小地图,Easy Minimap System MT-GPS插件
unity·游戏引擎
阿闽ooo3 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4963 天前
js设计模式 --- 工厂模式
设计模式
wy3258643643 天前
Unity 新输入系统InputSystem(基本操作)
unity·c#·游戏引擎
WarPigs3 天前
着色器multi_compile笔记
unity·着色器
ECHO飞跃 0123 天前
Unity2019 本地推理 通义千问0.5-1.5B微调导入
人工智能·深度学习·unity·llama
Unity游戏资源学习屋3 天前
【Unity UI资源包】GUI Pro - Casual Game 专为休闲手游打造的专业级UI资源包
ui·unity
冰凌糕3 天前
Unity3D Shader 顶点法线外扩实现描边效果
unity
小菱形_3 天前
【Unity】TimeLine
unity·游戏引擎