2010-06-23 38 views
0

我打造專業化工廠在Groovy中,此代碼的工作,但我認爲,這個代碼可以提高(或降低):如何在Groovy/Grails中定義工廠方法?

abstract class Processing { 

    abstract getDirName(); 

    abstract getFileType(); 

    abstract moveFile(); 

    abstract processFile(); 

    abstract openFile(); 

    abstract closeFile(); 
} 


class ProcessingBuilder { 

    def processingFactory 

    def orderProcess(String type) { 

     def process = processingFactory.buildProcessing(type); 

     process.getDirName(); 
     process.getFileType(); 
     process.moveFile(); 
     process.processFile(); 
     process.openFile(); 
     process.closeFile(); 

     return process; 
    } 

} 

class ProcessingFactory { 

     def buildProcessing(String type) { 

     def process = null; 

     if (type == "nanostring") { 
      process = new ProcessingNanoString(); 
     } else if (type == "flowcore") { 
      process = new ProcessingFlowCore(); 
     } 
     return process; 
    } 

} 

class ProcessingFlowCore extends Processing { 

    def getDirName() { 
     println "--> Get FlowCore directory structure" 
    } 

    def getFileType() { 
     println "--> Get FlowCore File Type" 
    } 

    def moveFile() { 
     println "--> Move FlowCore Files" 
    } 

    def processFile() { 
     println "--> Import FlowCore files to DB" 
    } 

    def openFile() { 
     println "--> Open FlowCore files" 
    } 

    def closeFile() { 
     println "--> Close FlowCore files" 
    } 

} 

要使用此工廠:

def processingFactory = new ProcessingFactory(); 

def processingBuilder = new ProcessingBuilder(processingFactory : processingFactory); 

def process = processingBuilder.orderProcess("flowcore"); 

有沒有更好的用groovy/grails建立工廠的方法?

我也嘗試錯誤,如果我嘗試在我ProcessingFlowCore類使用的服務:例如:

class ProcessingNanoString extends Processing { 

    def directoryToolsService 

    def getDirName() { 
     println "--> Get NanoString directory structure" 

     def dir = directoryToolsService.findDirPathByName(nanostring).directoryPath 

     return dir 
    } 

我得到一個:ERROR errors.GrailsExceptionResolver - 空對象不能調用方法findDirPathByName(nanostring)(如果我不在工廠,我可以致電此服務)。

爲什麼?

謝謝。

+0

快速回答最後一部分。您只能在應用程序中的某些地方獲得服務注入(控制器,服務,可能還有一兩個)。您不會在域中注入服務,也不會在src/groovy中創建類。 – billjamesdev 2010-06-24 04:46:54

+0

@Bill - 域類默認是可注入的,我很確定src/groovy中的任何類都是可注入的,儘管後者可能需要一些配置 – 2010-06-24 07:35:51

+0

我嘗試將我的工廠方法部分移至/ services,但是我得到同樣的錯誤。在我的文件夾服務中,我應該獲得服務注入。 – 2010-06-24 15:05:36

回答

3

如果使用你的服務的類在src/groovy中,那麼它將不會被自動注入。服務只會自動注入到artefact類中(例如,在grails-app下的任何東西)。要從普通班級獲得服務,請通過以下方式手動參考:

import org.codehaus.groovy.grails.commons.ApplicationHolder 

service = ApplicationHolder.getApplication().getMainContext().getBean('directoryToolsService')