Hands-On Design Patterns with Kotlin
eBook - ePub

Hands-On Design Patterns with Kotlin

Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin

Alexey Soshin

Share book
  1. 310 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Hands-On Design Patterns with Kotlin

Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin

Alexey Soshin

Book details
Book preview
Table of contents
Citations

About This Book

Make the most of Kotlin by leveraging design patterns and best practices to build scalable and high performing appsAbout This Book• Understand traditional GOF design patterns to apply generic solutions• Shift from OOP to FP; covering reactive and concurrent patterns in a step-by-step manner• Choose the best microservices architecture and MVC for your development environmentWho This Book Is ForThis book is for developers who would like to master design patterns with Kotlin to build efficient and scalable applications. Basic Java or Kotlin programming knowledge is assumedWhat You Will Learn• Get to grips with Kotlin principles, including its strengths and weaknesses• Understand classical design patterns in Kotlin• Explore functional programming using built-in features of Kotlin• Solve real-world problems using reactive and concurrent design patterns• Use threads and coroutines to simplify concurrent code flow• Understand antipatterns to write clean Kotlin code, avoiding common pitfalls• Learn about the design considerations necessary while choosing between architecturesIn DetailDesign patterns enable you as a developer to speed up the development process by providing you with proven development paradigms. Reusing design patterns helps prevent complex issues that can cause major problems, improves your code base, promotes code reuse, and makes an architecture more robust.The mission of this book is to ease the adoption of design patterns in Kotlin and provide good practices for programmers.The book begins by showing you the practical aspects of smarter coding in Kotlin, explaining the basic Kotlin syntax and the impact of design patterns. From there, the book provides an in-depth explanation of the classical design patterns of creational, structural, and behavioral families, before heading into functional programming. It then takes you through reactive and concurrent patterns, teaching you about using streams, threads, and coroutines to write better code along the wayBy the end of the book, you will be able to efficiently address common problems faced while developing applications and be comfortable working on scalable and maintainable projects of any size.Style and approachThis book explains design patterns in a step-by-step manner with clear and concise code examples

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Hands-On Design Patterns with Kotlin an online PDF/ePUB?
Yes, you can access Hands-On Design Patterns with Kotlin by Alexey Soshin in PDF and/or ePUB format, as well as other popular books in Informatique & Programmation en Java. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781788999595

Getting Familiar with Behavioral Patterns

This chapter discusses behavioral patterns with Kotlin. Behavioral patterns deal with how objects interact with one another.
We'll see how an object can behave in a totally different manner based on the situation, how objects can communicate without knowledge of one another, and how we can iterate over complex structures easily.
In this chapter, we will cover the following topics:
  • Strategy
  • Iterator
  • State
  • Command
  • Chain of responsibility
  • Interpreter
  • Mediator
  • Memento
  • Visitor
  • Template method
  • Observer

Strategy

Remember Maronic, the platformer we were designing in Chapter 3, Understanding Structural Patterns, while discussing the Facade design pattern?
Well, canary Michael, who acts as a game designer in our small indie game development company, came up with a great idea. What if we were to give our hero an arsenal of weapons to protect us from those horrible carnivorous snails?
Weapons all shoot projectiles (you don't want to get close to those dangerous snails) in the direction our hero is facing:
enum class Direction {
LEFT, RIGHT
}
All projectiles should have a pair of coordinates (our game is 2D, remember?) and a direction:
abstract class Projectile(private val x: Int,
private val y: Int,
private val direction: Direction)
If we were to shoot only one type of projectile, that would be simple, since we already covered the Factory pattern in Chapter 2, Working with Creational Patterns:
class OurHero {
private var direction = Direction.LEFT
private var x: Int = 42
private var y: Int = 173

fun shoot(): Projectile {
return object : Projectile(x, y, direction) {
// Draw and animate projectile here
}
}
}
But Michael wants our hero to have at least three different weapons:
  • Peashooter: Shoots small peas that fly straight. Our hero starts with it.
  • Pomegranate: Explodes when hitting an enemy, much like a grenade.
  • Banana: Returns like a boomerang when it reaches the end of the screen.
Come on, Michael, give us some slack! Can't you just stick with regular guns that all work the same?!

Fruit arsenal

First, let's discuss how we could solve this in the Java way.
In Java, we would have created an interface, that abstracts the changes. In our case, what changes is our hero's weapon:
interface Weapon {
fun shoot(x: Int,
y: Int,
direction: Direction): Projectile
}
Then all other weapons would implement this interface:
class Peashooter : Weapon {
override fun shoot(x: Int,
y: Int,
direction: Direction) =
object : Projectile(x, y, direction) {
// Fly straight
}
}

class Pomegranate : Weapon {
override fun shoot(x: Int,
y: Int,
direction: Direction) =
object : Projectile(x, y, direction) {
// Explode when you hit first enemy
}
}

class Banana : Weapon {
override fun shoot(x: Int,
y: Int,
direction: Direction) =
object : Projectile(x, y, direction) {
// Return when you hit screen border
}
}
Then our hero would hold a reference to a weapon (Peashooter at the beginning):
private var currentWeapon : Weapon = Peashooter()
It would delegate the actual shooting process to it:
fun shoot(): Projectile = currentWeapon.shoot(x, y, direction)
What's left is the ability to equip another weapon:
fun equip(weapon: Weapon) {
currentWeapon = weapon
}
And that's what the Strategy design pattern is all about. Now, our algorithms (Maronic's weapons, in that case) are interchangeable.

Citizen function

With Kotlin, there's a more efficient way to implement the same functionality using fewer classes. That's thanks to the fact that functions in Kotlin are first-class citizens.
What does that mean?
For one, we can assign functions to the variables of our class, like any other normal value.
It makes sense that you can assign a primitive value to your variable:
val x = 7
You could either assign an object to it:
var myPet = Canary("Michael")
So, why should you be able to assign a function to your variable? As follows:
val square = fun (x: Int): Long {
return (x * x).toLong()
}
With Kotlin, this is totally valid.

Switching sides

So, how do higher-order functions help us here?
First, we'll define a namespace for all our weapons. This is not mandatory, but helps to keep everything in check:
object Weapons {
// Functions we'll be there soon
}
Then, instead of classes, each of our w...

Table of contents