【Unity与23种设计模式】装饰模式(Decorator)

本文介绍了装饰模式的概念及其在C#中的应用。装饰模式允许在不修改原有代码的基础上为对象动态添加新功能,提高了代码的灵活性与稳定性。通过示例代码展示了如何使用装饰模式解决多继承问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

GoF中定义:

“动态地附加额外的责任给一个对象。装饰模式提供了一个灵活的选择,让子类可以用来扩展功能。”

 

装饰模式一般用来增加新功能

它可以避免更改已经实现的程序代码

从而增加系统的稳定性,也变得更加灵活

 

装饰模式解决了C#不能多继承的问题

它通过从父类继承出一个不符合“类封装时的抽象定义”的子类

持有一个父类的对象

然后与要添加的功能组合

从而实现添加新功能的目标

 

//形状父类
public abstract class IShape {
    public abstract void Draw();
    public abstract string GetPolygon();
}

//形状子类
public class Sphere : IShape {
    public override void Draw()
    {
        Debug.Log("draw Sphere");
    }
    public override string GetPolygon()
    {
        return "Sphere多边形";
    }
}
//“不符合类封装时的抽象定义”的子类
public abstract class IShapeDecorator : IShape {
    IShape m_Component;

    public IShapeDecorator(IShape theComponent) {
        m_Component = theComponent;
    }

    public override void Draw()
    {
        m_Component.Draw();
    }
    public override string GetPolygon()
    {
        return m_Component.GetPolygon();
    }
}
//能附加额外功能的类
public abstract class IAdditional {
    public abstract void DrawOnShape(IShape theShape);
}

public class Border : IAdditional {
    public override void DrawOnShape(IShape theShape)
    {
        Debug.Log("draw Border");
    }
}
//Border装饰者
public class BorderDecorator : IShapeDecorator {
    Border m_Border = new Border();

    public BorderDecorator(IShape theComponent) : base(theComponent) {}

    public override void Draw()
    {
        base.Draw();
        m_Border.DrawOnShape(this);
    }
    public override string GetPolygon()
    {
        return base.GetPolygon();
    }
}
//测试类
public class TestDecorator {
    void UnitTest() {
        Sphere theSphere = new Sphere();
        BorderDecorator theSphereWithBorder = new BorderDecorator(theSphere);
        theSphereWithBorder.Draw();
    }
}

 

 

 

文章整理自书籍《设计模式与游戏完美开发》 菜升达 著

转载于:https://www.cnblogs.com/fws94/p/7474203.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值