设计模式之工厂方法(FACTORY METHOD))(二)

( 接上页 )派生类为这个选拔基类( Seeding )分别建立一个实例来调用这些方法。我们现在建立这两个具体的选拔子类: StraightSeeding 类 CircleSeeding 类。 PrelimEvent 类将返回 CircleSeeding 类的实例, TimedFinalEvent 类则返回 StraightSeeding 类实例。

结构如下:

![](http://dev.csdn.net/article/26/C:/Documents and Settings\Administrator\My Documents\My Pictures\factory.bmp)

通过整个事件层次,可以看到 PrelimEvent 类、 TimedFinalEvent 类都包含 **_ getSeeding _ ** 方法, PrelimEvent 类将返回 CircleSeeding 类的实例, TimedFinalEvent 类则返回 StraightSeeding 类实例。在这个简单的例子当中我们并没有指出真正的工厂( Factory ),然而,实例化哪一个 Event 类决定了哪一个 Seeding 类将被实例化。

虽然它看起来像是在两个类之间存在一对一相应的通信。 但,这不是必需的。可以有许多不同类型的 Events 类但他们只使用少一部分 Seeding 类。

** Swimmer ** ** 类 ** ** **

** ** Swimmer 类包含一些游泳运动员的具体信息和在选拔之后修改运动员的组以及泳道的方 法。 Event类在数据库(在这个例子中为文本文件)读取运动员信息。当调用Event类的 **_ getSeeding _ ** 方法时 将这个运动员的集合传递到 Seeding 类。

** Events ** ** 类 ** ** **

** ** 我们已经定义了一个抽象基类,在实际的应用当中,我们只是使用它来读取游泳运动员的数据信息( 在这个例子中为文本文件 )。

** Prelimevent ** ** 类返回 ** ** CircleSeeding ** ** 实例 ** ** **


Public Class Prelimevent

Inherits Events

Dim sd As Seeding

Public Overrides Function getSeeding() As Seeding

Return New CircleSeeding(swmmers, numLanes)

End Function

Public Overrides Function isFinal() As Boolean

isFinal = False

End Function

Public Overrides Function isPrelim() As Boolean

isPrelim = True

End Function

Public Overrides Function isTimedFinal() As Boolean

isTimedFinal = False

End Function

Public Sub New ( ByVal Filename As String , ByVal lanes As Integer )

MyBase .New(Filename, lanes)

numLanes = lanes

End Sub

End Class

** TimedFinalEvent ** ** 类返回 ** ** StraightSeeding ** ** 实例 ** ** **

public Class TimedFinalEvent

Inherits Events

Public Sub New ( ByVal Filename As String , ByVal lanes As Integer )

MyBase .New(Filename, lanes)

End Sub

'------

Public Overrides Function getSeeding() As Seeding

Dim sd As Seeding

'create seeding and execute it

sd = New StraightSeeding(swmmers, numLanes)

sd.seed()

getSeeding = sd

End Function

'------

Public Overrides Function isFinal() As Boolean

isFinal = False

End Function

'------

Public Overrides Function isPrelim() As Boolean

isPrelim = False

End Function

'------

Public Overrides Function isTimedFinal() As Boolean

isTimedFinal = True

End Function

End Class

Published At
Categories with Web编程
Tagged with
comments powered by Disqus