Choosing a Strategy Through JSON Configuration

I am implementing a training agent in Java / Kotlin. Part of this agent functionality includes searching through a large list of possible options. There are many good ways to find space for opportunities, and I often change my mind about which one is the best. Therefore, I decided to implement it as a strategy template.

class Agent(val searchStrategy : SearchStrategy){
    fun search(input : InputGraph) : Result{
        return searchStrategy.search()
    }
}

interface SearchStrategy{
    fun search(input : InputGraph) : Result
}

class FastSearch : SearchStrategy{
    //implementation here
}

class AccurateSearch : SearchStrategy{
   // implementation here
}

class ExperimentalSerach : SearchStrategy{
  // implentation here
}

Recently, I decided to launch a large set of experiments that test the effectiveness of various system parameters. This is done using a python script that runs each experiment by running a compiled jar with another config.json file as an argument. Sort of:

{
    "numSamples" : 5000,
    "environmentDifficulty" : 3,
    "hazardProbability" : 0.4,
    //etc..
}

, . ? , config.json:

{
    "numSamples" : 5000,
    "environmentDifficulty" : 3,
    "hazardProbability" : 0.4,
    "agentStrategy": "FastSearch"
}

if if branch:

val searchStrategy = when(config.agentStrategy){
    "FastSearch" -> FastSearch()
    "AccurateSearch" -> AccurateSearch()
    "ExperimentalSearch" -> ExperimentalSearch()
val agent = agent(searchStrategy)

, / , . ?

+4
1

- :

val agentClass = classLoader.loadClass(config.agentStrategy)!!
val agent = agentClass.newInstance() as SearchStrategy

- , config :

class SearchStrategies(val strategies: List<SearchStrategy>){
    fun findForConfig(config:Config) = strategies.find { it.javaClass.name.contains(config.agentStrategy) }
}


//somewhere at boot time
val searchStrategies = SearchStrategies(listOf(FastSearch(), AccurateSearch()))


//when needed
val config = ...
val agent = searchStrategies.findForConfig(config)

, SPI, .

+5

Source: https://habr.com/ru/post/1654552/


All Articles