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

  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

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

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription.
No, books cannot be downloaded as external files, such as PDFs, for use outside of Perlego. However, you can download books within the Perlego app for offline reading on mobile or tablet. Learn more here.
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
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.
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.
Yes! You can use the Perlego app on both iOS or Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app.
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 Computer Science & Programming in Java. We have over one million books available in our catalogue for you to explore.

Information

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

  1. Title Page
  2. Copyright and Credits
  3. Dedication
  4. Packt Upsell
  5. Contributors
  6. Preface
  7. Getting Started with Kotlin
  8. Working with Creational Patterns
  9. Understanding Structural Patterns
  10. Getting Familiar with Behavioral Patterns
  11. Functional Programming
  12. Streaming Your Data
  13. Staying Reactive
  14. Threads and Coroutines
  15. Designed for Concurrency
  16. Idioms and Anti-Patterns
  17. Reactive Microservices with Kotlin
  18. Other Books You May Enjoy