dimanche 26 novembre 2017

Strategy - automatically register and select strategy by name

I have a lot of actions. All actions works with some Object/Context that passed in all actions. I want to use pattern Strategy/Policy.

interface Action {
    val name: String

    fun run(ctx: Context)
}

class Multiply(): Action {

    override name = "MULTIPLY"

    override fun run(ctx: Context) {
        writeToDb(ctx.id, ctx.number * 2)
    }
}

class Substract 

class SendNotification

etc...

So I want to register all strategies on startup. And select strategy from structure like Enum.

val action = selectAwaitingAction()
val ctx = selectCtxById(action.transaction_id)
perfromAction(ctx, actions.getByName(action.name))

fun performAction(ctx Context, action: Action) {
    action.run(ctx)
}

Is it possible in Java/Kotlin and what pattern should I use?

Aucun commentaire:

Enregistrer un commentaire