1.FlyWeight抽象类及具体类
Public MustInherit Class Flyweight
Public MustOverride Sub Operation(ByVal extrinsicstate As Integer)
End Class
'继承FleyWeight超类或实现FlyWeight接口,并为内部增加存储空间
Public Class ConcreteFlyweight
Inherits Flyweight
Public Overrides Sub Operation(ByVal extrinsicstate As Integer)
Console.WriteLine("具体Flyweight{0}:" & extrinsicstate)
End Sub
End Class
'不需要共享的FlyWeight子类。
Public Class UnsharedConcreteFlyweight
Inherits Flyweight
Public Overrides Sub Operation(ByVal extrinsicstate As Integer)
Console.WriteLine("不共享的具体Flyweight:" & extrinsicstate)
End Sub
End Class
2. FlyweightFactory,是一个享元工厂,用来创建并管理Flyweight对象。它主要是用来确保合理地共享Flyweight,当用户请求一个Flyweight时,FlyweightFactory对象提供一个已创建的实例或者创建一个(如果不存在的话)。
Public Class FlyWeightFactory
Private Flyweights As Hashtable = New Hashtable
Public Sub Flyweightfactory()
Flyweights.Add("X", New ConcreteFlyweight)
Flyweights.Add("Y", New ConcreteFlyweight)
Flyweights.Add("Z", New ConcreteFlyweight)
End Sub
Public Function GetFlyweight(ByVal key As String)
Return Flyweights(key)
End Function
End Class
3.客户端代码
Module Module1
Sub Main()
Dim extrinsicstate As Integer = 22
Dim f As FlyWeightFactory = New FlyWeightFactory
‘书中少了下面这一行,弱弱的Me调试了很久
f.Flyweightfactory()
Dim fx As Flyweight = f.GetFlyweight("X")
fx.Operation(extrinsicstate - 1)
extrinsicstate -= 1
Dim fy As Flyweight = f.GetFlyweight("Y")
fy.Operation(extrinsicstate - 1)
extrinsicstate -= 1
Dim fz As Flyweight = f.GetFlyweight("Z")
fz.Operation(extrinsicstate - 1)
extrinsicstate -= 1
Dim uf As UnsharedConcreteFlyweight = New UnsharedConcreteFlyweight
uf.Operation(extrinsicstate - 1)
Console.Read()
End Sub
End Module