Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scala adapter pattern - maxondev.com
public interface Adaptee {
void doAdaptee();
}
public interface Adaptor {
void doAdaptor();
}
class Client{
private final Adaptor adaptor;
public Client(Adaptor adaptor) {
this.adaptor = adaptor;
}
public void foo() {
this.adaptor.doAdaptor();
}
}
public class AdapteeAdapter implements Adaptor{
private final Adaptee adaptee;
public AdapteeAdapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void doAdaptor() {
this.adaptee.doAdaptee();
}
}
Adaptee adaptee = null;
Adaptor adaptor = new AdapteeAdapter(adaptee);
Client client = new Client(adaptor);
case class Celsius(degrees: Double)
case class Fahrenheit(degrees: Double)
trait ToCelsius[From] {
def convert(source: From): Celsius
}
class FahrenheitConverter extends ToCelsius[Fahrenheit] {
override def convert(source: Fahrenheit): Celsius = new Celsius((source.degrees - 32) * 5 / 9)
}
class CelsiusIdentityConverter extends ToCelsius[Celsius] {
override def convert(source: Celsius): Celsius = source
}
class AirConditioner {
def setTemperature[T](degrees: T)(implicit ev: ToCelsius[T]): Unit = {
val converter = implicitly[ToCelsius[T]]
val asCelsius = converter.convert(degrees)
println(s"Set to $asCelsius")
}
}
implicit val fahrenheitToCelsius = new FahrenheitConverter
implicit val celsiusIdentity = new CelsiusIdentityConverter
val airConditioner = new AirConditioner()
airConditioner.setTemperature(new Fahrenheit(75))
airConditioner.setTemperature(new Celsius(23))
case class Celsius(degrees: Double)
case class Fahrenheit(degrees: Double)
class AirConditioner{
def setTemperature(celsius: Celsius) = println(s"Set to ${celsius.degrees}")
}
implicit def fahrenheit2Celsius(fahrenheit: Fahrenheit): Celsius = new Celsius((fahrenheit.degrees - 32) * 5/9)
new AirConditioner().setTemperature(new Fahrenheit(75))
trait Adaptor {
def doAdaptor
}
class Client(adaptor: Adaptor){
def foo = adaptor.doAdaptor
}
trait Adaptee {
def doAdaptee
}
implicit def adaptee2Adaptor(adaptee: Adaptee): Adaptor = {
new Adaptor {
override def doAdaptor: Unit = adaptee.doAdaptee
}
}
val adaptee: Adaptee = ???
val client = new Client(adaptee)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment