TDC2017|SP - Trilha Android Usando Delegations no Kotlin

106 visualizações

Publicada em

Usando Delegations no Kotlin

Publicada em: Educação
  • Seja o primeiro a comentar

  • Seja a primeira pessoa a gostar disto

TDC2017|SP - Trilha Android Usando Delegations no Kotlin

  1. 1. Delegations no Kotlin
  2. 2. Felipe Rodrigues Android Developer Stone Pagamentos @lipitchu facebook.com/filpgame @filpgame filpgame@gmail.com
  3. 3. O Problema class Client { String firstName, lastName, username, email; }
  4. 4. O Problema interface Auth { void login(); } class Client implements Auth { String firstName, lastName, username, email; @Override public void login() { } }
  5. 5. O Problema interface Auth { void login(); } interface Access { boolean isAdmin(); } class Client implements Auth, Access { String firstName, lastName, username, email; @Override public void login() { } @Override public boolean isAdmin() { } }
  6. 6. O Problema interface Auth { void login(); } interface Access { boolean isAdmin(); } interface Finances { long balance(); } class Client implements Auth, Access, Finances { String firstName, lastName, username, email; @Override public void login() { } @Override public boolean isAdmin() { } @Override public long balance() { } }
  7. 7. Delegation? “ Delegation is an implementation mechanism in which an object forwards or delegates a request to another object. ”
  8. 8. interface Loggable { public void log(String message); }
  9. 9. interface Loggable { public void log(String message); } class ConsoleLogger implements Loggable { @Override public void log(String message) { System.out.println(message); } } class ToastLogger implements Loggable { Context context; public ToastLogger(Context context) { this.context = context; } @Override public void log(String message) { Utils.showToast(context, message); } }
  10. 10. interface Loggable { public void log(String message); } class ConsoleLogger implements Loggable { @Override public void log(String message) { System.out.println(message); } } class ToastLogger implements Loggable { Context context; public ToastLogger(Context context) { this.context = context; } @Override public void log(String message) { Utils.showToast(context, message); } } class Worker implements Loggable { public Loggable logger; public Worker(Loggable logger) { this.logger = logger; } @Override public void log(String message) { logger.log(message); } public void doWork() { log( "Working"); } }
  11. 11. interface Loggable { public void log(String message); } class ConsoleLogger implements Loggable { @Override public void log(String message) { System.out.println(message); } } class ToastLogger implements Loggable { Context context; public ToastLogger(Context context) { this.context = context; } @Override public void log(String message) { Utils.showToast(context, message); } } class Worker implements Loggable { public Loggable logger; public Worker(Loggable logger) { this.logger = logger; } @Override public void log(String message) { logger.log(message); } public void doWork() { log( "Working"); } } Worker worker = new Worker(new ConsoleLogger()); worker.logger = new ToastLogger(getContext()); worker.doWork();
  12. 12. Pra que usar isso? - Reusabilidade;
  13. 13. Pra que usar isso? - Reusabilidade; - Baixo Acoplamento;
  14. 14. Pra que usar isso? - Reusabilidade; - Baixo Acoplamento; - Herança Dinâmica;
  15. 15. Pra que usar isso? - Reusabilidade; - Baixo Acoplamento; - Herança Dinâmica; - Separação de Responsabilidade;
  16. 16. interface Loggable { public void log(String message); } class ConsoleLogger implements Loggable { @Override public void log(String message) { System.out.println(message); } } class ToastLogger implements Loggable { Context context; public ToastLogger(Context context) { this.context = context; } @Override public void log(String message) { Utils.showToast(context, message); } } class Worker implements Loggable { public Loggable logger; public Worker(Loggable logger) { this.logger = logger; } @Override public void log(String message) { logger.log(message); } public void doWork() { log( "Working"); } } Worker worker = new Worker(new ConsoleLogger()); worker.logger = new ToastLogger(getContext()); worker.doWork();
  17. 17. interface Loggable { fun log(message: String) } class ConsoleLogger : Loggable { override fun log(msg: String) = println(msg) } class ToastLogger(val context: Context) : Loggable { override fun log(msg: String) = toast(msg) } class Worker(var logger: Loggable) : Loggable by logger { fun doWork() { log("Working...") } } val worker = Worker(ConsoleLogger()) worker.logger = ToastLogger(context) worker.doWork()
  18. 18. Delegated Properties
  19. 19. Como usar class NameDelegate() { var name: String = "Felipe" operator fun getValue(ref: Any?, prop: KProperty<*>): String { println("valor '$value' de '${prop.name}'sendo entregue para $ref") return name } operator fun setValue(ref: Any?, prop: KProperty<*>, value: String) { println("’$value’ atribuido à ‘${prop.name}’ em $ref.'") name = value } } val name: String by NameDelegate()
  20. 20. Como usar class NameDelegate() { var name: String = "Felipe" operator fun getValue(ref: Any?, prop: KProperty<*>): String { println("valor '$value' de '${prop.name}'sendo entregue para $ref") return name } operator fun setValue(ref: Any?, prop: KProperty<*>, value: String) { println("’$value’ atribuido à ‘${prop.name}’ em $ref.'") name = value } } val name: String by NameDelegate()
  21. 21. Como usar class NameDelegate() { var name: String = "Felipe" operator fun getValue(ref: Any?, prop: KProperty<*>): String { println("valor '$value' de '${prop.name}'sendo entregue para $ref") return name } operator fun setValue(ref: Any?, prop: KProperty<*>, value: String) { println("’$value’ atribuido à ‘${prop.name}’ em $ref.'") name = value } } var name: String by NameDelegate()
  22. 22. Como usar class NameDelegate(): ReadWriteProperty<Any?, String> { // ou ReadOnlyProperty var name: String = "Felipe" override fun getValue(ref: Any?, prop: KProperty<*>): String { println("valor '$value' de '${prop.name}'sendo entregue para $ref") return name } override fun setValue(ref: Any?, prop: KProperty<*>, value: String) { println("’$value’ atribuido à ‘${prop.name}’ em $ref.'") name = value } } val name: String by NameDelegate()
  23. 23. Delegations Properties Padrão ● Lazy val database: Database by lazy { println("created!") Database() } fun main(args: Array<String>) { println(database.isConnected()) println(database.isConnected()) }
  24. 24. Delegations Properties Padrão ● Lazy val database: Database by lazy { println("created!") Database() } fun main(args: Array<String>) { println(database.isConnected()) println(database.isConnected()) } Output: created! false false
  25. 25. Delegations Properties Padrão ● Observable import kotlin.properties.Delegates class User { var name: String by Delegates.observable( "Sicrano") { prop, oldValue, newValue -> println("$oldValue -> $newValue") } } val user = User() user.name = "Fulano" user.name = "Beltrano"
  26. 26. Delegations Properties Padrão ● Observable import kotlin.properties.Delegates class User { var name: String by Delegates.observable( "Sicrano") { prop, oldValue, newValue -> println("$oldValue -> $newValue") } } val user = User() user.name = "Fulano" user.name = "Beltrano" Output: Sicrano -> Fulano Fulano -> Beltrano
  27. 27. Delegations Properties Padrão ● Armazenar em um Map class User(val map: Map<String, Any?>) { val name: String by map val age: Int by map } val user = User(mapOf( "name" to "John Doe", "age" to 25 )) println("Name: ${user.name}, Age: ${user.age}")
  28. 28. Delegations Properties Padrão ● Armazenar em um Map class User(val map: Map<String, Any?>) { val name: String by map val age: Int by map } val user = User(mapOf( "name" to "John Doe", "age" to 25 )) println("Name: ${user.name}, Age: ${user.age}") Output: Name: John Doe, Age: 25
  29. 29. Libs usando delegations ● KotPref (github.com/chibatching/Kotpref) object UserInfo : KotprefModel() { var name by stringPref() var code by nullableStringPref() var age by intPref(default = 14) var highScore by longPref() var rate by floatPref() val prizes by stringSetPref { val set = TreeSet<String>() set.add( "Beginner") set } } UserInfo.name = "User" UserInfo.code = "Test"
  30. 30. Dúvidas?

×