Skip to content

Adapters

Jonathan edited this page Feb 16, 2018 · 6 revisions

Adapter pattern is used to wrap platform types and adapt them to Sandstone types. SandstoneCommon uses AdapterHelper as the helper of Adapter classes, the work of this project is to implement classes, adapter caching, adapter factory and type conversion (such as Text conversion).

Adapter interface

Suppose that we have to adapt platform.a.CoffeeMachine of Platform A to common API common.CoffeeMaker:

Platform A:

package platform.a

class CoffeeMachine {
  fun giveMeCoffee(): Drink
}

Common API:

package common

interface Producer<T> {
  fun produce(): T
}

interface CoffeeMaker : Producer<Drink> {
  fun make() = this.produce()
}

Adapter:

interface CoffeeMachineAdapter : Adapter<platform.a.CoffeeMachine>, common.CoffeeMaker {
    override fun produce(): Drink =
        this.adapterManager.convert<platform.a.Drink, common.Drink>(this.adapteeInstance.giveMeCoffee(), this)
}

Registering

To register the adapter you will need to have an instance of AdapterManager, luckily SandstoneCommon provides a common AdapterManager instance. Registering:

val adapters = Adapters.adapters

// First the converter of Drink data type
adapters.registerConverter<platform.a.Drink, common.Drink>(DrinkConverter) 

// Now adapters
adapters.register(fromInterface<CoffeMachineAdapter, common.CoffeeMaker, platform.a.CoffeeMachine>())

Obs: The convention is to register all converters before all adapters.

Using

val coffeeMachine = ...
val drinkProducer: Producer<Drink> = adapter.adapt<CoffeeMachine, CoffeeMaker>(coffeeMachine)

Concrete adapters

We heavily recommend the Adapter interface, but you can also write concrete adapters (if you think that it fits better for the purpose), but these adapters should extend Adapter<T> or AdapterBase<T>, to register them in the system you should do:

adapters.register<common.CoffeeMaker, platform.a.CoffeeMachine>() { adaptee, manager -> 
  // Invoke adapter constructor or factory method, the adaptee is the instance to adapt and
  // the manager is the AdapterManager instance that invoked this factory function
}

Adaptation or conversion

Conversion should be used when the type that is being converted is a Data Type (e.g Text, Location), in other hand, adaptation is more used in game objects (such as entities, blocks, items, world).

Clone this wiki locally