views:

54

answers:

1

I buid a factory in groovy, this code works, but I think, this code can be improved (or reduced) :

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"
    }

}

To use this factory :

def processingFactory = new ProcessingFactory();

def processingBuilder = new ProcessingBuilder(processingFactory : processingFactory);

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

Is there a better way to build a factory with groovy/grails ?

I also experiment errors, if I try to use services in my ProcessingFlowCore Class : ex :

class ProcessingNanoString extends Processing {

  def directoryToolsService

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

      def dir = directoryToolsService.findDirPathByName(nanostring).directoryPath

      return dir
    }

I get a : ERROR errors.GrailsExceptionResolver - Cannot invoke method findDirPathByName(nanostring) on null object.(I can call this service if I'm not in the factory).

Why ?

Thanks.

+1  A: 

If the class using your service is in src/groovy, then it won't be injected automatically. Services are only injected automatically into artefact classes (e.g. anything under grails-app). To get a service from a regular class, get a reference to it manually with this:

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

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