简体   繁体   中英

How to replace this pattern with a functional alternative?

I have the following pattern in Scala:

object CurrentDriver {

  private var webDriver: WebDriver = null

  def invalidate = {
    webDriver.quit()
    webDriver = null
  }

  def getWebDriver = {
    if (webDriver==null)
      webDriver = DriverFactory.buildWebDriver
    webDriver
  }
}

Its not functional, it has a var, and the invalidate method returns a Unit. The singleton object is needed as it's referred to by a few classes which are instantiated using reflection by a framework, so i have not way to pass arguments to them. Hence they need to call getWebDriver to get access to the same instance of the WebDriver. I need to periodically (after each test scenario, which consists of multiple test functions) quit and re-create a new WebDriver, which is handled by the invalidate method.

I suggest something like an around block.

 object CurrentDriver {
      def around(f: WebDriver => Unit) = {
          val webDriver: WebDriver = DriverFactory.buildWebDriver
          f(webDriver) // your tests
          webDriver.quit()
      }
 }

For each of your tests blocks, you can combine the block with the around function.

For example:

 def testFunc(webDriver: WebDriver) = around{ 
   assert(2 ==2)
   // do something with webDriver
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM