桥接模式同样可用在多种数据采集方式的场合,在有生产过程实时数据采集时,经常遇到多种数据采集的接口。为适应这种情况,可以采用桥接模式,其结构如图所示。
针对不同的数据源有不同的数据采集方式,有的采集系统需要直接从文件中读取数据,有的需要从远程Web服务器读取数据,有的需要从实时数据库读取数据,有的需要从关系数据库读取数据等。数据采集系统是低层平台,在上层应用中需要各种方式的显示形式,例如流程图、表格、曲线图和趋势图等。每种显示方式模块都可能从不同的数据源接收数据,即不同类型的数据源和数据显示方式应该可以任意组合。
以一个来源于实际项目的例子说明。我们需要在Web页面上显示流程图,并且需要生成XML格式的流程图文件。其中采用简单工厂获得数据来源,数据来源标志保存在Web.config文件中。
下图所示为应用的局部结构,其中采用了桥接模式。
下面是部分代码,限于篇幅,仅列出结构部分。
定义clsAbstractReadData类,其中定义了需要获得数据的结构:
具体的读取类实现ReadData方法。下面是从文本文件中读取数据,其中给出了读取用逗号分隔数据的方法:1 Imports System.IO 2 Imports System.Net 3 Imports System.Text 4 Public MustInherit Class clsAbstractReadDataClass clsAbstractReadData 5 Public MustOverride Function ReadData()Function ReadData(ByVal strDate AsstrDate As DataSet 6 Protected mySourceDs As DataSet 7 Public Sub New()Sub New( ) 8 MySourceDS = New DataSet 9 Dim dt As DataTable 10 ‘这里定义数据结构,省略 11 End Sub 12 End Class 13
下面是产生读取对象的简单工厂:1 Public Class clsReadDataFromFileClass clsReadDataFromFile 2 Inherits ClsAbstractReadData 3 Private datafilepath As String 4 5 Public Sub New()Sub New(ByVal strpath As String) 6 MyBase.New( ) 7 Datafilepath = strpath 8 End Sub 9 Public Overrides Function ReadData()Function ReadData(ByVal strDate As String) As 10 System.Date.DataSet 11 ‘调用ReadDataFromFile从具体的文件中读取数据,省略 12 Return mysourceds 13 End Function 14 Private Sub ReadDataFromFile()Sub ReadDataFromFile(ByVal fn As String,,ByVal dt AsDataTable,ByVal 15 cn As Integer ) 16 ‘fn 数据文件名 17 ‘dt DtatTable 18 ‘cn 字段数 19 Dim fileNumber As Integer 20 FileNumber = FreeFile( ) 21 FileOpen(fileNumber, fn, OpenMode.Input) 22 Dim NextLine As String 23 I = 1 24 Do Until EOF(fileNumber) 25 NextLine = LineInput(fileNumber) 26 If I > 1 And Trim(NextLine) <> “ ” Then 27 Dim j As Integer 28 Dim r As DataRow = dt.NewRow 29 Dim s As String = “ ,” 30 Dim sp As Char( ) = s.ToCharArray 31 Dim rs As String( ) = NextLine.Split(sp) 32 For j = 0 To cn – 1 33 Dim v As String 34 Try 35 V = rs ( j ) 36 r.Item( j ) = Trim( v ) 37 Catch ex As Exception 38 r.Item( j ) = “ ” 39 End Try 40 Next 41 Dt.Rows.Add(r) 42 End If 43 I = I + 1 44 Loop 45 FileClose(fileNumber) 46End Sub 47Private Function IsFileExist()Function IsFileExist (ByVal fn As String) As Boolean 48 If FileSystem.Dir (fn) = “ ” Then Return False 49 Return True 50End Function 51End Class 52
1 Public Class clsReaDataFactoryClass clsReaDataFactory 2 Pbulic Shared Function getDataReader()Function getDataReader ( ) As clsAbstractReadData 3 Dim datafilepath As String = 4 ConfigurationSettings.AppSettings (“DataFilePath”) 5 Dim strDataType As String = ConfigurationSettings.AppSettings (“DataType”) 6 Dim strHttp As String = ConfigurationSettings.AppSettings (“DataURL”) 7 Select Case strDataType 8 Case “http” 9 Dim mrd As clsReadDataFromRemoteFile 10 Mrd = New clsReadDataFromRemoteFile (strHttp) 11 Return mrd 12 Case Else 13 Dim mrd As clsReadDataFromFile 14 Mrd = New clsReadDataFromFile(datafilepath) 15 Return mrd 16 End Select 17 End Function 18end class