在 VFP 中你是否遇到过这样的场景:明明已经释放了表单,但是表单仍旧顽固的显示在屏幕中?好吧,这其实是因为某些引用没有被释放。在该设计模式下,更准确的说,是在代码中存在双向引用。
其实,还有一种更普遍的场景:你很烦躁的编写表单中的代码,为什么烦躁呢?因为一个控件要调用其他控件中的方法,密密麻麻,像蜘蛛网一样的毫无规律,小心翼翼的写完了,需求变了,开始骂娘......
是时候让中介者模式出场了。
简单的理解中介者模式,其实就是将蜘蛛网一样的控件调用改成星型结构。所有的控件围成一圈,中间添加一个中介者。各控件和中介者之间存在双向引用。
是不是感觉变的相对清晰了?
作为中间镇场子的中介者,我们可以先定义一个接口(模板):
Define Class IMediator As Custom
*** <summary>
*** 中介者统一的调度方法
*** </summary>
*** <param name="toObject">发送者对象</param>
*** <param name="tcMessage">事件</param>
Procedure Notify(toObject As Object, tcMessage As String)
Endproc
Procedure Release()
Endproc
Enddefine
基于此模式的特点,那么,所有外围组件至少需要继承自下面的模板:
Define Class BaseComponent As Custom
oMediator = .Null.
Procedure Init(toMediator As IMediator)
This.oMediator = m.toMediator
Endproc
Procedure SetMediator(toMediator As IMediator)
This.oMediator = m.toMediator
Endproc
Procedure Release()
Release This
Endproc
Enddefine
假设存在以下两个组件:
Define Class ComponentA As BaseComponent
Procedure DoA()
This.oMediator.Notify(This, "ONE")
Endproc
Procedure DoB()
This.oMediator.Notify(This, "TWO")
Endproc
Enddefine
Define Class ComponentB As BaseComponent
Procedure Doc()
? "ONE"
Endproc
Procedure DoD()
? "TWO"
Endproc
Enddefine
那么具体的中介者大概可以是以下的样子:
Define Class ConcreteMediator As IMediator
oComponentA = .Null.
oComponentB = .Null.
Procedure Init(toComponentA As BaseComponent, toComponentB As BaseComponent)
With This
.oComponentA = m.toComponentA
.oComponentB = m.toComponentB
Endwith
Endproc
Procedure Notify(toObject As Object, tcMessage As String)
Do Case
Case m.tcMessage == "ONE"
This.oComponentB.Doc()
Case m.tcMessage == "TWO"
This.oComponentB.DoD()
Endcase
Endproc
Procedure Release()
With This
If Vartype(.oComponentA) = "O"
.oComponentA.oMediator = .Null.
.oComponentB.oMediator = .Null.
.oComponentA = .Null.
.oComponentB = .Null.
Endif
EndWith
Release This
Endproc
Enddefine
所以,最后我们在程序中的代码大概就是以下的样子:
Public loComponentA As ComponentA, loComponentB As ComponentB, loConcreteMediator As ConcreteMediator
m.loComponentA = Createobject("ComponentA")
m.loComponentB = Createobject("ComponentB")
m.loConcreteMediator = Createobject("ConcreteMediator", m.loComponentA, m.loComponentB)
m.loComponentA.SetMediator(m.loConcreteMediator)
m.loComponentB.SetMediator(m.loConcreteMediator)
m.loComponentA.DoA()
m.loComponentA.DoB()
Clear
? Vartype(m.loConcreteMediator)
? Vartype(m.loComponentA)
? Vartype(m.loComponentB)
m.loConcreteMediator.Release()
m.loComponentA.Release()
m.loComponentB.Release()
? Vartype(m.loConcreteMediator)
? Vartype(m.loComponentA)
? Vartype(m.loComponentB)
Debug
VFP 和 C#/X# 的垃圾回收机制不同,因此,在 .NET 平台,代码没有 VFP 中那样“复杂”(具体参看后续文章......),但是,该设计模式在 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. 腾讯云 版权所有