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

Partager le livre
  1. 310 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

Hands-On Design Patterns with Kotlin

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

Alexey Soshin

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

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

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Hands-On Design Patterns with Kotlin est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Hands-On Design Patterns with Kotlin par Alexey Soshin en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Informatique et Programmation en Java. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
2018
ISBN
9781788999595
Édition
1

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 des matiĂšres