我有以下代碼。我有兩個不同的工作,它們調用下面提到的處理器類。這兩項工作幾乎完全相同,但只有在最後一步纔會有所不同。目前,我正在基於布爾變量'createReport'處理它。我想將90%的通用功能提取到一個類中。設計模式:提取常見功能
我想過模板模式。但是,我如何將repositoryA的依賴注入抽象類?
Imports log4net
Imports System
Imports System.Collections.Generic
Public Interface IProcessor
Sub Process(path As String, includeCache As Boolean, createReport As Boolean)
End Interface
Public Class Processor
Implements IProcessor
Private ReadOnly _repositoryA As IRepositoryA
Private ReadOnly _repositoryB As IRepositoryB
Private ReadOnly _logger As ILog
Public Sub New(repositoryA As IRepositoryA, repositoryB As IRepositoryB, logger As ILog)
If repositoryA Is Nothing Then
Throw New ArgumentNullException("repositoryA")
End If
If repositoryB Is Nothing Then
Throw New ArgumentNullException("repositoryB")
End If
If logger Is Nothing Then
Throw New ArgumentNullException("logger")
End If
_repositoryA = repositoryA
_repositoryB = repositoryB
_logger = logger
End Sub
Public Sub Process(folderPaths As String, includeCache As Boolean, createReport As Boolean) Implements IProcessor.Process
_logger.Info("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
If String.IsNullOrEmpty(folderPaths) Then
Throw New ArgumentNullException("folderPaths")
End If
Dim paths() As String = folderPaths.Split(New Char() {";"c})
For Each path As String In paths
Dim cList As List(Of Container) = _repositoryA.GetContainers(path, includeCache)
For Each container As Container In cList
If Not container.IsDeleted Then
Dim assetList As List(Of Asset) = _repositoryA.GetAssets(container.ContainerID)
If Not assetList Is Nothing Then
For Each asset As Asset In assetList
ProcessAsset(asset, createReport)
Next
End If
End If
Next
Next
_logger.Info("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
End Sub
Private Sub ProcessAsset(asset As Asset, createReport As Boolean)
'Again some common business logic
'at last depending on value of createReport
If createReport Then
CreateReport(asset)
Else
SyncAsset(asset, ...other arguments)
End If
End Sub
Private Sub SyncAsset(asset As asset, ..other arguments)
'business logic. Dependency on _repositoryB here
End Sub
Private Sub CreateReport(asset As asset)
'business logic
End Sub
End Class
感謝您的幫助提前
問候, Suyog
請使用語法高亮顯示 – 2014-09-04 18:51:40
我沒有看到問題。模板方法聽起來像一個合理的方法。什麼阻止你在抽象類中定義存儲庫變量? – 2014-09-05 07:23:44