装饰器模式类似于俄罗斯套娃,但又不是“容器套容器”的静态方式实现。
相较于后者,装饰器模式结构更清晰,也更容易扩展。但是对于可视组件进行“装饰”,会增加布局的复杂性,以及考虑状态的同步。因此,对于简单的场景,可以直接继承,而对于复杂的场景则可以选择其他的设计模式。
因此,该模式的最佳应用应该是针对非可视组件的“装饰”。
按照完整的模式描述,首先,我们需要确定具体实现和装饰器共同的基类:
Define Class Component as Custom
Procedure DoSomething()
EndProc
EndDefine
具体的实现就可以这样定义:
Define Class ConcreteComponent as Component
Procedure DoSomething()
? "具体实现需要执行的业务逻辑"
endproc
EndDefine
考虑对具体实现可能进行不同的“装饰”,所以,需要定义具体装饰器的基类:
Define Class Decorator As Component
Protected oComponent
oComponent = .NULL.
Procedure SetComponent(toComponent As Component)
EndProc
Procedure DoSomething()
If !IsNull(This.oComponent) And Vartype(This.oComponent) = "O"
This.oComponent.DoSomething()
EndIf
EndProc
EndDefine
因此,第一个装饰器的定义就可以是:
Define Class ConcreteDecorator As Decorator
Procedure DoSomething()
This.CustomDecoration()
DoDefault()
EndProc
PROCEDURE CustomDecoration()
? "装饰器附加的业务逻辑"
ENDPROC
EndDefine
所以,最终的代码就是:
Local loConcreteComponent As ConcreteComponent, loConcreteDecorator As ConcreteDecorator
m.loConcreteComponent = CreateObject("ConcreteComponent")
m.loConcreteDecorator = CreateObject("ConcreteDecorator")
m.loConcreteDecorator.SetComponent(m.loConcreteComponent)
m.loConcreteDecorator.DoSomething()
以上为该设计模式的 VFP 实现基本原理。
未完待续......
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有