SlideShare a Scribd company logo
1 of 21
Design
Patterns
with
Kotlin
Alexey Soshin, November 2018
Intro
● “Design Patterns” by “Gang of Four” was written back in ‘92. This is the only edition of the
book. All examples in the book are either in C++ or SmallTalk
● Somebody once said that “design patterns are workarounds for shortcomings of
particular language”. But he was fan of Lisp, so we can disregard that saying
● Disclaimer: all your favorite design patterns, including Singleton, will work in Kotlin as-is.
Still, there are often better ways to achieve the same goal
Singleton
“Ensure a class has only one instance, and provide a global point of access to it.”
public final class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
In Java:
volatile
synchronized
instance
static
private static
Singleton - continued
object Singleton
Taken directly from Scala
CounterSingleton.INSTANCE.increment();
When called from Java, instead of usual .getInstance() uses INSTANCE field
CounterSingleton.increment()
Very concise usage syntax:
In Kotlin:
Builder
“Allows constructing complex objects step by step”
ElasticSearch API, for example, just LOVES builders...
client.prepareSearch("documents")
.setQuery(query(dressQuery))
.addSort(RANK_SORT)
.addSort(SEARCHES_SORT)
.get()
Builder - continued
In Kotlin, often can be replaced with combination of default parameters and .apply()
function
data class Mail(val to: String,
var title: String = "",
var message: String = "",
var cc: List<String> = listOf(),
var bcc: List<String> = listOf(),
val attachments: List<java.io.File> = listOf()) {
fun message(m: String) = apply {
message = m
} // No need to "return this"
}
val mail = Mail("bill.gates@microsoft.com")
.message("How are you?").apply {
cc = listOf("s.ballmer@microsoft.com")
bcc = listOf("pichais@gmail.com")
}
Less boilerplate, same readability
Proxy
“Provides a substitute or placeholder for another object”
Decorator and Proxy have different purposes but
similar structures. Both describe how to provide a
level of indirection to another object, and the
implementations keep a reference to the object to
which they forward requests.
In Kotlin: by keyword is used for such delegation
val image: File by lazy {
println("Fetching image over network")
val f = File.createTempFile("cat", ".jpg")
URL(url).openStream().use {
it.copyTo(BufferedOutputStream(f.outputStream()))
}.also { println("Done fetching") }
f
}
Iterator
“Abstracts traversal of data structures in a linear way”
class MyDataStructure<T> implements Iterable<T> { ... }
In Java, this is built-in as Iterable interface
Same will work also in Kotlin
class MyDataStructure<T>: Iterable<T> { ... }
Iterator - continued
But in order not to have to implement too many interfaces (Android API, anyone?), you
can use iterator() function instead:
class MyDataStructure<T> {
operator fun iterator() = object: Iterator<T> {
override fun hasNext(): Boolean {
...
}
override fun next(): T {
...
}
}
}
State
“Allows an object to alter its behavior when its internal state changes”
sealed class Mood
object Still : Mood() //
class Aggressive(val madnessLevel: Int) : Mood()
object Retreating : Mood()
object Dead : Mood()
Kotlin sealed classes are great for state management
Since all descendants of a sealed class must reside in the same file, you also
avoid lots of small files describing states in your project
State - continued
Best feature is that compiler makes sure that you check all states when using
sealed class
override fun seeHero() {
mood = when(mood) {
is Still -> Aggressive(2)
is Aggressive -> Retreating
is Retreating -> Aggressive(1)
// Doesn't compile, when must be exhaustive
}
}
override fun seeHero() {
mood = when(mood) {
is Still -> Aggressive(2)
is Aggressive -> Retreating
is Retreating -> Aggressive(1)
is Dead -> Dead // Better
}
}
You must either specify all conditions, or use else block
Strategy
“Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets
the algorithm vary independently from the clients that use it.”
class OurHero {
private var direction = Direction.LEFT
private var x: Int = 42
private var y: Int = 173
// Strategy
var currentWeapon = Weapons.peashooter
val shoot = fun() {
currentWeapon(x, y, direction)
}
}
In Kotlin functions are first class citizens.
If you want to replace a method - replace a method, don’t talk.
Strategy - continued
object Weapons {
val peashooter = fun(x: Int, y: Int, direction: Direction) {
// Fly straight
}
val banana = fun(x: Int, y: Int, direction: Direction) {
// Return when you hit screen border
}
val pomegranate = fun(x: Int, y: Int, direction: Direction) {
// Explode when you hit first enemy
}
}
You can encapsulate all available strategies
And replace them at will
val h = OurHero()
h.shoot() // peashooter
h.currentWeapon = Weapons.banana
h.shoot() // banana
Deferred value
Not once I’ve heard JavaScript developers state that they don’t need design patterns in
JavaScript.
But Deferred value is one of the concurrent design patterns, and it’s widely used nowadays
Also called Future or Promise
with(GlobalScope) {
val userProfile: Deferred<String> = async {
delay(Random().nextInt(100).toLong())
"Profile"
}
}
val profile: String = userProfile.await()
In Kotlin provided as part of coroutines library:
Fan Out
“Deliver message to multiple destinations without halting the process”
Producer
Consumer 1 Consumer 2 Consumer 3
“r” “n” “d”
Used to distribute work
Each message delivered to only consumer,
semi-randomly
Kotlin coroutine library provides
ReceiveChannel for that purpose
fun CoroutineScope.producer(): ReceiveChannel<String> = produce {
for (i in 1..1_000_000) {
for (c in 'a' .. 'z') {
send(c.toString()) // produce next
}
}
}
Fan Out - continued
“Deliver message to multiple destinations without halting the process”
Consumers can iterate over the channel, until it’s closed
fun CoroutineScope.consumer(id: Int,
channel: ReceiveChannel<String>) = launch {
for (msg in channel) {
println("Processor #$id received $msg")
}
}
Here we distribute work between 4 consumers:
val producer = producer()
val processors = List(4) {
consumer(it, producer)
}
for (p in processors) {
p.join()
}
Fan In
Similar to Fan Out pattern, Fan In relies on coroutines library and channels
“Receive messages from multiple sources concurrently”
fun CoroutineScope.collector(): SendChannel<Int> = actor {
for (msg in channel) {
println("Got $msg")
}
}
Multiple producers are able to send to the same channel
fun CoroutineScope.producer(id: Int, channel: SendChannel<Int>) = launch {
repeat(10_000) {
channel.send(id)
}
}
Fan In - continued
val collector = collector()
val producers = List(4) {
producer(it, collector)
}
producers.forEach { it.join() }
Multiple producers are able to send to the same channel
Outputs:
...
Got 0
Got 0
Got 1
Got 2
Got 3
Got 0
Got 0
...
Summary
● Design patterns are everywhere
● Like any new language (unless it’s Go), Kotlin learns from shortcomings of its
predecessors
● Kotlin has a lot of design patterns built in, as either idioms, language constructs or
extension libraries
● Design patterns are not limited by GoF book
References
https://sourcemaking.com/design_patterns
https://refactoring.guru/design-patterns
Question time
Thanks a lot for attending!

More Related Content

What's hot

Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvmArnaud Giuliani
 
Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Arnaud Giuliani
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นคลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นFinian Nian
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternNitin Bhide
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersBartosz Kosarzycki
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Brief Summary Of C++
Brief Summary Of C++Brief Summary Of C++
Brief Summary Of C++Haris Lye
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design PatternVarun Arora
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Abu Saleh
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8Dhaval Dalal
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxingGeetha Manohar
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parametersKnoldus Inc.
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2Abbas Ajmal
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of androidDJ Rausch
 

What's hot (20)

Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017
 
Kotlin
KotlinKotlin
Kotlin
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นคลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
 
Iterator
IteratorIterator
Iterator
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design pattern
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Lazy java
Lazy javaLazy java
Lazy java
 
Brief Summary Of C++
Brief Summary Of C++Brief Summary Of C++
Brief Summary Of C++
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
 
Java vs kotlin
Java vs kotlinJava vs kotlin
Java vs kotlin
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of android
 

Similar to Design Patterns with Kotlin

What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?Squareboat
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for KotlinTechMagic
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
Container Classes
Container ClassesContainer Classes
Container Classesadil raja
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentJayaprakash R
 
Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers STX Next
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance Coder Tech
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Mohamed Nabil, MSc.
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
IntroductiontoprogramminginscalaAmuhinda Hungai
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoArnaud Giuliani
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyMobileAcademy
 
Oop lect3.pptx
Oop lect3.pptxOop lect3.pptx
Oop lect3.pptxMrMudassir
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to KotlinMagda Miu
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 

Similar to Design Patterns with Kotlin (20)

What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Container Classes
Container ClassesContainer Classes
Container Classes
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekito
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
 
Oop lect3.pptx
Oop lect3.pptxOop lect3.pptx
Oop lect3.pptx
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 

Recently uploaded

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 

Recently uploaded (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 

Design Patterns with Kotlin

  • 2. Intro ● “Design Patterns” by “Gang of Four” was written back in ‘92. This is the only edition of the book. All examples in the book are either in C++ or SmallTalk ● Somebody once said that “design patterns are workarounds for shortcomings of particular language”. But he was fan of Lisp, so we can disregard that saying ● Disclaimer: all your favorite design patterns, including Singleton, will work in Kotlin as-is. Still, there are often better ways to achieve the same goal
  • 3. Singleton “Ensure a class has only one instance, and provide a global point of access to it.” public final class Singleton { private static volatile Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } In Java: volatile synchronized instance static private static
  • 4. Singleton - continued object Singleton Taken directly from Scala CounterSingleton.INSTANCE.increment(); When called from Java, instead of usual .getInstance() uses INSTANCE field CounterSingleton.increment() Very concise usage syntax: In Kotlin:
  • 5. Builder “Allows constructing complex objects step by step” ElasticSearch API, for example, just LOVES builders... client.prepareSearch("documents") .setQuery(query(dressQuery)) .addSort(RANK_SORT) .addSort(SEARCHES_SORT) .get()
  • 6. Builder - continued In Kotlin, often can be replaced with combination of default parameters and .apply() function data class Mail(val to: String, var title: String = "", var message: String = "", var cc: List<String> = listOf(), var bcc: List<String> = listOf(), val attachments: List<java.io.File> = listOf()) { fun message(m: String) = apply { message = m } // No need to "return this" } val mail = Mail("bill.gates@microsoft.com") .message("How are you?").apply { cc = listOf("s.ballmer@microsoft.com") bcc = listOf("pichais@gmail.com") } Less boilerplate, same readability
  • 7. Proxy “Provides a substitute or placeholder for another object” Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests. In Kotlin: by keyword is used for such delegation val image: File by lazy { println("Fetching image over network") val f = File.createTempFile("cat", ".jpg") URL(url).openStream().use { it.copyTo(BufferedOutputStream(f.outputStream())) }.also { println("Done fetching") } f }
  • 8. Iterator “Abstracts traversal of data structures in a linear way” class MyDataStructure<T> implements Iterable<T> { ... } In Java, this is built-in as Iterable interface Same will work also in Kotlin class MyDataStructure<T>: Iterable<T> { ... }
  • 9. Iterator - continued But in order not to have to implement too many interfaces (Android API, anyone?), you can use iterator() function instead: class MyDataStructure<T> { operator fun iterator() = object: Iterator<T> { override fun hasNext(): Boolean { ... } override fun next(): T { ... } } }
  • 10. State “Allows an object to alter its behavior when its internal state changes” sealed class Mood object Still : Mood() // class Aggressive(val madnessLevel: Int) : Mood() object Retreating : Mood() object Dead : Mood() Kotlin sealed classes are great for state management Since all descendants of a sealed class must reside in the same file, you also avoid lots of small files describing states in your project
  • 11. State - continued Best feature is that compiler makes sure that you check all states when using sealed class override fun seeHero() { mood = when(mood) { is Still -> Aggressive(2) is Aggressive -> Retreating is Retreating -> Aggressive(1) // Doesn't compile, when must be exhaustive } } override fun seeHero() { mood = when(mood) { is Still -> Aggressive(2) is Aggressive -> Retreating is Retreating -> Aggressive(1) is Dead -> Dead // Better } } You must either specify all conditions, or use else block
  • 12. Strategy “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.” class OurHero { private var direction = Direction.LEFT private var x: Int = 42 private var y: Int = 173 // Strategy var currentWeapon = Weapons.peashooter val shoot = fun() { currentWeapon(x, y, direction) } } In Kotlin functions are first class citizens. If you want to replace a method - replace a method, don’t talk.
  • 13. Strategy - continued object Weapons { val peashooter = fun(x: Int, y: Int, direction: Direction) { // Fly straight } val banana = fun(x: Int, y: Int, direction: Direction) { // Return when you hit screen border } val pomegranate = fun(x: Int, y: Int, direction: Direction) { // Explode when you hit first enemy } } You can encapsulate all available strategies And replace them at will val h = OurHero() h.shoot() // peashooter h.currentWeapon = Weapons.banana h.shoot() // banana
  • 14. Deferred value Not once I’ve heard JavaScript developers state that they don’t need design patterns in JavaScript. But Deferred value is one of the concurrent design patterns, and it’s widely used nowadays Also called Future or Promise with(GlobalScope) { val userProfile: Deferred<String> = async { delay(Random().nextInt(100).toLong()) "Profile" } } val profile: String = userProfile.await() In Kotlin provided as part of coroutines library:
  • 15. Fan Out “Deliver message to multiple destinations without halting the process” Producer Consumer 1 Consumer 2 Consumer 3 “r” “n” “d” Used to distribute work Each message delivered to only consumer, semi-randomly Kotlin coroutine library provides ReceiveChannel for that purpose fun CoroutineScope.producer(): ReceiveChannel<String> = produce { for (i in 1..1_000_000) { for (c in 'a' .. 'z') { send(c.toString()) // produce next } } }
  • 16. Fan Out - continued “Deliver message to multiple destinations without halting the process” Consumers can iterate over the channel, until it’s closed fun CoroutineScope.consumer(id: Int, channel: ReceiveChannel<String>) = launch { for (msg in channel) { println("Processor #$id received $msg") } } Here we distribute work between 4 consumers: val producer = producer() val processors = List(4) { consumer(it, producer) } for (p in processors) { p.join() }
  • 17. Fan In Similar to Fan Out pattern, Fan In relies on coroutines library and channels “Receive messages from multiple sources concurrently” fun CoroutineScope.collector(): SendChannel<Int> = actor { for (msg in channel) { println("Got $msg") } } Multiple producers are able to send to the same channel fun CoroutineScope.producer(id: Int, channel: SendChannel<Int>) = launch { repeat(10_000) { channel.send(id) } }
  • 18. Fan In - continued val collector = collector() val producers = List(4) { producer(it, collector) } producers.forEach { it.join() } Multiple producers are able to send to the same channel Outputs: ... Got 0 Got 0 Got 1 Got 2 Got 3 Got 0 Got 0 ...
  • 19. Summary ● Design patterns are everywhere ● Like any new language (unless it’s Go), Kotlin learns from shortcomings of its predecessors ● Kotlin has a lot of design patterns built in, as either idioms, language constructs or extension libraries ● Design patterns are not limited by GoF book
  • 21. Question time Thanks a lot for attending!

Editor's Notes

  1. © https://sourcemaking.com/design_patterns/singleton
  2. © https://sourcemaking.com/design_patterns/singleton
  3. © https://refactoring.guru/design-patterns/builder
  4. © https://refactoring.guru/design-patterns/builder
  5. © https://sourcemaking.com/design_patterns/proxy
  6. © https://en.wikipedia.org/wiki/Fan-out_(software) © https://kotlinlang.org/docs/reference/coroutines/channels.html#fan-out
  7. © https://en.wikipedia.org/wiki/Fan-out_(software) © https://kotlinlang.org/docs/reference/coroutines/channels.html#fan-out