Advertisement
Kostiggig

Untitled

Jul 6th, 2022
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.26 KB | None | 0 0
  1. interface Printer {
  2.    
  3.     fun print(data: String)
  4.  
  5.     class Log : Printer  {
  6.         override fun print(data: String) {
  7.             Log.d("TAG","Print some info to log - $data")
  8.         }
  9.     }
  10.     class Firebase(private val firebaseAnalytics: FirebaseAnalytics) : Printer {
  11.         override fun print(data: String) {
  12.             Log.d("TAG","Firebase data print - $data")
  13.         }
  14.     }
  15.    
  16.     class Empty : Printer {
  17.         override fun print(data: String) = Unit
  18.     }
  19. }
  20.  
  21. interface Data {
  22.  
  23.     fun changePrinter(printer: Printer)
  24.    
  25.     fun print()
  26.  
  27.     class Base(
  28.         private val data: String
  29.     ) : Data {
  30.        
  31.         private var printer: Printer = Printer.Empty
  32.        
  33.         override fun changePrinter(printer: Printer) {
  34.             this.printer = printer
  35.         }
  36.        
  37.         override fun print() = printer.print(data)
  38.        
  39.        
  40.     }
  41. }
  42.  
  43. fun main() {
  44.     // Using Strategy pattern
  45.     val data = Data.Base("Data from network")
  46.     val logPrinter = Printer.Log()
  47.    
  48.     data.changePrinter(logPrinter)
  49.    
  50.     data.printData() // print the following text: Print some info to log - Data from network
  51.    
  52.     val firebasePrinter = Printer.Firebase(Firebase.getAnalytics())
  53.    
  54.     data.changePrinter(firebasePrinter)
  55.    
  56.     data.printData() // print the following text: Firebase data print - Data from network
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement