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

Buch teilen
  1. 310 Seiten
  2. English
  3. ePUB (handyfreundlich)
  4. Über iOS und Android verfügbar
eBook - ePub

Hands-On Design Patterns with Kotlin

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

Alexey Soshin

Angaben zum Buch
Buchvorschau
Inhaltsverzeichnis
Quellenangaben

Über dieses Buch

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

Häufig gestellte Fragen

Wie kann ich mein Abo kündigen?
Gehe einfach zum Kontobereich in den Einstellungen und klicke auf „Abo kündigen“ – ganz einfach. Nachdem du gekündigt hast, bleibt deine Mitgliedschaft für den verbleibenden Abozeitraum, den du bereits bezahlt hast, aktiv. Mehr Informationen hier.
(Wie) Kann ich Bücher herunterladen?
Derzeit stehen all unsere auf Mobilgeräte reagierenden ePub-Bücher zum Download über die App zur Verfügung. Die meisten unserer PDFs stehen ebenfalls zum Download bereit; wir arbeiten daran, auch die übrigen PDFs zum Download anzubieten, bei denen dies aktuell noch nicht möglich ist. Weitere Informationen hier.
Welcher Unterschied besteht bei den Preisen zwischen den Aboplänen?
Mit beiden Aboplänen erhältst du vollen Zugang zur Bibliothek und allen Funktionen von Perlego. Die einzigen Unterschiede bestehen im Preis und dem Abozeitraum: Mit dem Jahresabo sparst du auf 12 Monate gerechnet im Vergleich zum Monatsabo rund 30 %.
Was ist Perlego?
Wir sind ein Online-Abodienst für Lehrbücher, bei dem du für weniger als den Preis eines einzelnen Buches pro Monat Zugang zu einer ganzen Online-Bibliothek erhältst. Mit über 1 Million Büchern zu über 1.000 verschiedenen Themen haben wir bestimmt alles, was du brauchst! Weitere Informationen hier.
Unterstützt Perlego Text-zu-Sprache?
Achte auf das Symbol zum Vorlesen in deinem nächsten Buch, um zu sehen, ob du es dir auch anhören kannst. Bei diesem Tool wird dir Text laut vorgelesen, wobei der Text beim Vorlesen auch grafisch hervorgehoben wird. Du kannst das Vorlesen jederzeit anhalten, beschleunigen und verlangsamen. Weitere Informationen hier.
Ist Hands-On Design Patterns with Kotlin als Online-PDF/ePub verfügbar?
Ja, du hast Zugang zu Hands-On Design Patterns with Kotlin von Alexey Soshin im PDF- und/oder ePub-Format sowie zu anderen beliebten Büchern aus Informatique & Programmation en Java. Aus unserem Katalog stehen dir über 1 Million Bücher zur Verfügung.

Information

Jahr
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...

Inhaltsverzeichnis