Share
Embed
Gang of Four Patterns in Kotlin
How would some of the most famous design patterns in computer science look like in Kotlin?
Instead of converting Java Code, I will try to find a simpler, easier or more idiomatic way to solve the same problem each pattern is solving.
by Lovis Möller
presented on December 12, 2017 @yelp
Kotlin User Group Hamburg
December 12, 2017
Transcript
115 slides
-
Patterns Structural Creational Behavioral Adapter Bridge Decorator Façade Flyweight Composite
Proxy Factory method Abstract factory Singleton Builder Prototype Interpreter Template method Observer Visitor Iterator Command Memento Strategy Mediator State Chain of responsibility -
Patterns Structural Creational Behavioral Adapter Bridge Decorator Façade Flyweight Composite
Proxy Factory method Abstract factory Singleton Builder Prototype Interpreter Template method Observer Visitor Iterator Command Memento Strategy Mediator State Chain of responsibility -
Strategy Define a family of algorithms, encapsulate each one, and
make them interchangeable -
interface Discount { double discountedPrice(double raw); } public static class
Customer { final String name; final double fee; final Discount discount; public Customer(String name, double fee, Discount discount) { this.name = name; this.fee = fee; this.discount = discount; } public double pricePerMonth() { return discount.discountedPrice(fee); } } -
interface Discount { double discountedPrice(double raw); } public static class
Customer { final String name; final double fee; final Discount discount; public Customer(String name, double fee, Discount discount) { this.name = name; this.fee = fee; this.discount = discount; } public double pricePerMonth() { return discount.discountedPrice(fee); } } -
interface Discount { double discountedPrice(double raw); } public static class
Customer { final String name; final double fee; final Discount discount; public Customer(String name, double fee, Discount discount) { this.name = name; this.fee = fee; this.discount = discount; } public double pricePerMonth() { return discount.discountedPrice(fee); } } -
interface Discount { double discountedPrice(double raw); } public static class
NoDiscount implements Discount { @Override public double discountedPrice(double raw) { return raw; } } -
interface Discount { double discountedPrice(double raw); } public static class
NoDiscount implements Discount { @Override public double discountedPrice(double raw) { return raw; } } public static class StudentDiscount implements Discount { @Override public double discountedPrice(double raw) { return 0.5 * raw; } } -
Customer student = new Customer("Ned", 10, new StudentDiscount()); Customer regular
= new Customer("John", 10, new NoDiscount()); System.out.println(String.format("%s pays %.2f per month", student.name, student.pricePerMonth())); System.out.println(String.format("%s pays %.2f per month", regular.name, regular.pricePerMonth())); -
Customer student = new Customer("Ned", 10, new StudentDiscount()); Customer regular
= new Customer("John", 10, new NoDiscount()); System.out.println(String.format("%s pays %.2f per month", student.name, student.pricePerMonth())); System.out.println(String.format("%s pays %.2f per month", regular.name, regular.pricePerMonth())); -
Customer student = new Customer("Ned", 10, new StudentDiscount()); Customer regular
= new Customer("John", 10, new NoDiscount()); System.out.println(String.format("%s pays %.2f per month", student.name, student.pricePerMonth())); System.out.println(String.format("%s pays %.2f per month", regular.name, regular.pricePerMonth())); -
typealias Discount = (Double) Double class Customer(val name: String,
val fee: Double, val discount: Discount) { fun pricePerMonth() = discount(fee) } -
typealias Discount = (Double) Double class Customer(val name: String,
val fee: Double, val discount: Discount) { fun pricePerMonth() = discount(fee) } val studentDiscount = { raw: Double raw/2 } val noDiscount = { raw: Double raw } -
typealias Discount = (Double) Double class Customer(val name: String,
val fee: Double, val discount: Discount) { fun pricePerMonth() = discount(fee) } val studentDiscount = { raw: Double raw/2 } val noDiscount = { raw: Double raw } val student = Customer("Ned", 10.0, studentDiscount) val regular = Customer("John", 10.0, noDiscount) println("${student.name} pays %.2f per month".format(student.pricePerMonth())) println("${regular.name} pays %.2f per month".format(regular.pricePerMonth())) -
typealias Discount = (Double) Double class Customer(val name: String,
val fee: Double, val discount: Discount) { fun pricePerMonth() = discount(fee) } val studentDiscount = { raw: Double raw/2 } val noDiscount = { raw: Double raw } val student = Customer("Ned", 10.0, studentDiscount) val regular = Customer("John", 10.0, noDiscount) println("${student.name} pays %.2f per month".format(student.pricePerMonth())) println("${regular.name} pays %.2f per month".format(regular.pricePerMonth())) -
typealias Discount = (Double) Double class Customer(val name: String,
val fee: Double, val discount: Discount) { fun pricePerMonth() = discount(fee) } val studentDiscount = { raw: Double raw/2 } val noDiscount = { raw: Double raw } val student = Customer("Ned", 10.0, studentDiscount) val regular = Customer("John", 10.0, noDiscount) println("${student.name} pays %.2f per month".format(student.pricePerMonth())) println("${regular.name} pays %.2f per month".format(regular.pricePerMonth())) -
Builder Separate the construction of a complex object from its
representation so that the same construction process can create different representations -
public interface CarBuilder { void setDoors(int doors); void setColor(String color);
Car build(); } public static CarBuilder newBuilder(){ … } -
public interface CarBuilder { void setDoors(int doors); void setColor(String color);
Car build(); } public final class Car { private int doors; private String color; public Car(int doors, String color) { this.doors = doors; this.color = color; } } public static CarBuilder newBuilder(){ … } -
class Car(var color: String = “red”, var doors = 3,
) val car = Car( color = “green”, doors = 5, ) -
val car = Car().apply { color = "yellow" doors =
5 } class Car() { var color: String = "red" var doors = 3 } -
class Car() { var color: String = "red" var doors
= 3 } val config: Car.() Unit = { color = "yellow" doors = 5 } -
class Car() { var color: String = "red" var doors
= 3 } val config: Car.() Unit = { color = "yellow" doors = 5 } val car = Car().apply(config) -
class Car() { var color: String = "red" var doors
= 3 } val config: Car.() Unit = { color = "yellow" doors = 5 } val car = Car() .apply(COBALT_BLUE) .apply(LEATHER_PACKAGE) .apply(TIRES_18_INCH) -
Singleton Ensure a class only has one instance, and provide
a global point of access to it -
public class Dictionary { private static final Dictionary INSTANCE =
new Dictionary(); private Dictionary() { … } public static Dictionary get() { return INSTANCE; } public void addWord(String word, String definition){ … } public String getDefinition(String word) { … } } -
public class Dictionary { private static final Dictionary INSTANCE =
new Dictionary(); private Dictionary() { … } public static Dictionary get() { return INSTANCE; } public void addWord(String word, String definition){ … } public String getDefinition(String word) { … } } -
public class Dictionary { private static final Dictionary INSTANCE =
new Dictionary(); private Dictionary() { … } public static Dictionary get() { return INSTANCE; } public void addWord(String word, String definition){ … } public String getDefinition(String word) { … } } -
public class Dictionary { private static final Dictionary INSTANCE =
new Dictionary(); private Dictionary() { … } public static Dictionary get() { return INSTANCE; } public void addWord(String word, String definition){ … } public String getDefinition(String word) { … } } -
object Dictionary { fun addWord(word: String, definition: String) { …
} fun getDefinition(word: String): String { … } } -
Prototype Specify the kinds of objects to create using a
prototypical instance, and create new objects by copying this prototype -
/** * A class implements the <code>Cloneable</code> interface to *
indicate to the {@link java.lang.Object#clone()} method that it * is legal for that method to make a * field-for-field copy of instances of that class. * <p> * Invoking Object's clone method on an instance that does not implement the * <code>Cloneable</code> interface results in the exception * <code>CloneNotSupportedException</code> being thrown. * <p> * By convention, classes that implement this interface should override * <tt>Object.clone</tt> (which is protected) with a public method. * See {@link java.lang.Object#clone()} for details on overriding this * method. * <p> * Note that this interface does <i>not</i> contain the <tt>clone</tt> method. * Therefore, it is not possible to clone an object merely by virtue of the * fact that it implements this interface. Even if the clone method is invoked * reflectively, there is no guarantee that it will succeed. * */ public interface Cloneable { } -
/** * A class implements the <code>Cloneable</code> interface to *
indicate to the {@link java.lang.Object#clone()} method that it * is legal for that method to make a * field-for-field copy of instances of that class. * <p> * Invoking Object's clone method on an instance that does not implement the * <code>Cloneable</code> interface results in the exception * <code>CloneNotSupportedException</code> being thrown. * <p> * By convention, classes that implement this interface should override * <tt>Object.clone</tt> (which is protected) with a public method. * See {@link java.lang.Object#clone()} for details on overriding this * method. * <p> * Note that this interface does <i>not</i> contain the <tt>clone</tt> method. * Therefore, it is not possible to clone an object merely by virtue of the * fact that it implements this interface. Even if the clone method is invoked * reflectively, there is no guarantee that it will succeed. * */ public interface Cloneable { } Clone is broken http://www.artima.com/intv/bloch13.html -
data class EMail( var recipient: String, var subject: String?, var
message: String? ) -
data class EMail( var recipient: String, var subject: String?, var
message: String? ) -
data class EMail( var recipient: String, var subject: String?, var
message: String? ) val mail = EMail("[email protected]", "Hello", "Don't know what to write.") -
data class EMail( var recipient: String, var subject: String?, var
message: String? ) val mail = EMail("[email protected]", "Hello", "Don't know what to write.") val copy1 = mail.copy(recipient = "[email protected]") -
data class EMail( var recipient: String, var subject: String?, var
message: String? ) val mail = EMail("[email protected]", "Hello", "Don't know what to write.") val copy1 = mail.copy(recipient = "[email protected]") val copy2 = mail.copy(recipient = "[email protected]", subject = "Re: Hello") -
data class EMail( var recipient: String, var subject: String?, var
message: String? ) val mail = EMail("[email protected]", "Hello", "Don't know what to write.") val copy1 = mail.copy(recipient = "[email protected]") val copy2 = mail.copy(recipient = "[email protected]", subject = "Re: Hello") val copy3 = mail.copy() -
Iterator Provide a way to access the elements of an
aggregate object sequentially without exposing its underlying representation. -
public class Sentence { private final List<String> words; public Sentence(List<String>
words) { this.words = words; } public List<String> getWords() { return words; } } -
public class Sentence { private final List<String> words; public Sentence(List<String>
words) { this.words = words; } public List<String> getWords() { return words; } } Sentence sentence = new Sentence(words); for (String word : sentence.getWords()) { // } -
public class Sentence { private final List<String> words; public Sentence(List<String>
words) { this.words = words; } public List<String> getWords() { return words; } } Sentence sentence = new Sentence(words); for (String word : sentence.getWords()) { //not so cool } -
public static class Sentence { … } public class IterableSentence
extends Sentence implements Iterable<String> { public IterableSentence(List<String> words) { super(words); } @Override public Iterator<String> iterator() { return getWords().iterator(); } } -
public static class Sentence { … } public class IterableSentence
extends Sentence implements Iterable<String> { public IterableSentence(List<String> words) { super(words); } @Override public Iterator<String> iterator() { return getWords().iterator(); } } Sentence sentence = new IterableSentence(words); for (String word : sentence) { //better } -
class Sentence(val words: List<String>) operator fun Sentence.iterator(): Iterator<String> = words.iterator()
val sentence = Sentence(words) for(word in sentence){ } -
class OtherSentence( private val words: List<String> ): Iterable<String> by words
val otherSentence = OtherSentence(words) for(word in otherSentence){ … } -
class OtherSentence( private val words: List<String> ): Iterable<String> by words
val otherSentence = OtherSentence(words) for(word in otherSentence){ … } otherSentence.forEach { word … } if(otherSentence.contains(“X-Mas”)){ … } -
Visitor Represent an operation to be performed on the elements
of an object structure. A Visitor lets you define a new operation without changing the classes of the elements on which it operates -
interface Shape { <T> T accept(ShapeVisitor<T> visitor); } public static
class Square implements Shape { final double side; public Square(double side) { this.side = side; } @Override public <T> T accept(ShapeVisitor<T> visitor) { return visitor.visit(this); } } public static class Circle implements Shape { final double radius; public Circle(double radius) { this.radius = radius; } @Override public <T> T accept(ShapeVisitor<T> visitor) { return visitor.visit(this); } } public static class Rectangle implements Shape { final double width; final double height; public Rectangle(double width, double height) { this.width = width; this.height = height; } @Override public <T> T accept(ShapeVisitor<T> visitor) { return visitor.visit(this); } } interface ShapeVisitor<T> { T visit(Square element); T visit(Circle element); T visit(Rectangle element); } public static class AreaVisitor implements ShapeVisitor<Double> { public Double visit(Square element) { return element.side * element.side; } public Double visit(Circle element) { return Math.PI * element.radius * element.radius; } public Double visit(Rectangle element) { return element.height * element.width; } } public static class PerimeterVisitor implements ShapeVisitor<Double> { public Double visit(Square element) { return 4 * element.side; } public Double visit(Circle element) { return 2 * Math.PI * element.radius; } public Double visit(Rectangle element) { return (2 * element.height + 2 * element.width); } } -
interface Shape { <T> T accept(ShapeVisitor<T> visitor); } public static
class Square implements Shape { final double side; public Square(double side) { this.side = side; } @Override public <T> T accept(ShapeVisitor<T> visitor) { return visitor.visit(this); } } public static class Circle implements Shape { final double radius; public Circle(double radius) { this.radius = radius; } @Override public <T> T accept(ShapeVisitor<T> visitor) { return visitor.visit(this); } } public static class Rectangle implements Shape { final double width; final double height; public Rectangle(double width, double height) { this.width = width; this.height = height; } @Override public <T> T accept(ShapeVisitor<T> visitor) { return visitor.visit(this); } } interface ShapeVisitor<T> { T visit(Square element); T visit(Circle element); T visit(Rectangle element); } public static class AreaVisitor implements ShapeVisitor<Double> { public Double visit(Square element) { return element.side * element.side; } public Double visit(Circle element) { return Math.PI * element.radius * element.radius; } public Double visit(Rectangle element) { return element.height * element.width; } } public static class PerimeterVisitor implements ShapeVisitor<Double> { public Double visit(Square element) { return 4 * element.side; } public Double visit(Circle element) { return 2 * Math.PI * element.radius; } public Double visit(Rectangle element) { return (2 * element.height + 2 * element.width); } } “Elements” “Visitors” -
sealed class Shape() class Square(val side: Double) : Shape() class
Circle(val radius: Double) : Shape() class Rectangle(val width: Double, val height: Double) : Shape() -
sealed class Shape() class Square(val side: Double) : Shape() class
Circle(val radius: Double) : Shape() class Rectangle(val width: Double, val height: Double) : Shape() val perimeterVisitor = { shape: Shape when (shape) { is Rectangle 2 * shape.height + 2 * shape.width is Circle 2 * Math.PI * shape.radius is Square 4 * shape.side } } -
sealed class Shape() class Square(val side: Double) : Shape() class
Circle(val radius: Double) : Shape() class Rectangle(val width: Double, val height: Double) : Shape() val perimeterVisitor = { shape: Shape when (shape) { is Rectangle 2 * shape.height + 2 * shape.width is Circle 2 * Math.PI * shape.radius is Square 4 * shape.side } } val figures = listOf(Circle(4.0), Square(5.0), Rectangle(6.0, 7.0)) val totalArea = figures.sumByDouble { perimeterVisitor(it) } -
sealed class Shape() class Square(val side: Double) : Shape() class
Circle(val radius: Double) : Shape() class Rectangle(val width: Double, val height: Double) : Shape() val perimeterVisitor = { shape: Shape when (shape) { is Rectangle 2 * shape.height + 2 * shape.width is Circle 2 * Math.PI * shape.radius else } } val figures = listOf(Circle(4.0), Square(5.0), Rectangle(6.0, 7.0)) val totalArea = figures.sumByDouble { perimeterVisitor(it) } -
sealed class Shape() class Square(val side: Double) : Shape() class
Circle(val radius: Double) : Shape() class Rectangle(val width: Double, val height: Double) : Shape() val perimeterVisitor = { shape: Shape when (shape) { is Rectangle 2 * shape.height + 2 * shape.width is Circle 2 * Math.PI * shape.radius } } val figures = listOf(Circle(4.0), Square(5.0), Rectangle(6.0, 7.0)) val totalArea = figures.sumByDouble { perimeterVisitor(it) } ‘when’ expression must be exhaustive -
sealed class Shape() class Square(val side: Double) : Shape() class
Circle(val radius: Double) : Shape() class Rectangle(val width: Double, val height: Double) : Shape() val perimeterVisitor = { shape: Shape when (shape) { is Rectangle 2 * shape.height + 2 * shape.width is Circle 2 * Math.PI * shape.radius is Square 4 * shape.side } } val figures = listOf(Circle(4.0), Square(5.0), Rectangle(6.0, 7.0)) val totalArea = figures.sumByDouble { perimeterVisitor(it) } -
public interface Text { void draw(); } public class PrintedText
implements Text { … } -
public interface Text { void draw(); } public class PrintedText
implements Text { … } public abstract class TextEffect implements Text { protected Text decorated; … } -
public interface Text { void draw(); } public class PrintedText
implements Text { … } public abstract class TextEffect implements Text { protected Text decorated; … } public class Background extends TextEffect { public Background(Text decorated) { super(decorated); } @Override public void draw() { … decorated.draw(); } … } -
public interface Text { void draw(); } public class PrintedText
implements Text { … } public abstract class TextEffect implements Text { protected Text decorated; … } public class Background extends TextEffect { public Background(Text decorated) { super(decorated); } @Override public void draw() { … decorated.draw(); } … } -
new Background( new PrintedText("With Background") ).draw(); new Background( new Underline(
new PrintedText(“Underlined with Background”) ) ).draw(); -
new Background( new PrintedText("With Background") ).draw(); new Background( new Underline(
new PrintedText(“Underlined with Background”) ) ).draw(); new Background( new Underline( new Blinking( new PrintedText(“Underlined with Background, that blinks!”) ) ) ).draw(); -
interface Text { fun draw() } class DefaultText(val text: String)
: Text { override fun draw() { … } } -
interface Text { fun draw() } class DefaultText(val text: String)
: Text { override fun draw() { … } } fun Text.underline(decorated: Text.() Unit) { … this.decorated() … } -
interface Text { fun draw() } class DefaultText(val text: String)
: Text { override fun draw() { … } } fun Text.underline(decorated: Text.() Unit) { … this.decorated() … } -
interface Text { fun draw() } class DefaultText(val text: String)
: Text { override fun draw() { … } } fun Text.underline(decorated: Text.() Unit) { … this.decorated() … } -
interface Text { fun draw() } class DefaultText(val text: String)
: Text { override fun draw() { … } } fun Text.underline(decorated: Text.() Unit) { //decorate this.decorated() //decorate } -
interface Text { fun draw() } class DefaultText(val text: String)
: Text { override fun draw() { … } } fun Text.underline(decorated: Text.() Unit) { //decorate this.decorated() //decorate } fun Text.background(decorated: Text.() Unit) { //decorate this.decorated() //decorate } -
Decorator…? The Decorator pattern as demonstrated in GoF is just
a very convoluted way to achieve functions composition. ~ Mario Fusco -
Function composition f(x) g(x) …made simple! (But probably not really
correct. Sorry, not sorry, mathematicians ) -
Function composition f(x) g(x) h(x) = (f ∘ g)(x) …made
simple! (But probably not really correct. Sorry, not sorry, mathematicians ) -
Function composition f(x) g(x) h(x) = (f ∘ g)(x) =
g(f(x)) …made simple! (But probably not really correct. Sorry, not sorry, mathematicians ) -
Function composition f(x) = x + 1 g(x) = x2
h(x) = (f ∘ g)(x) = g(f(x)) = (x + 1)2 …made simple! (But probably not really correct. Sorry, not sorry, mathematicians ) -
Function composition f(x) = x + 1 g(x) = x2
h(x) = (f ∘ g)(x) = g(f(x)) = (x + 1)2 …made simple! (But probably not really correct. Sorry, not sorry, mathematicians ) fun h(x: Int) = g(f(x)) -
fun underline(text: String) = … fun background(text: String) = …
val text = underline(background(“Functional?”)) -
fun underline(text: String): String = … fun background(text: String): String
= … val text = underline(background(“Functional?”)) -
fun underline(text: String): String = … fun background(text: String): String
= … val text: String = underline(background(“Functional?”)) -
fun underline(text: String): String = … fun background(text: String): String
= … val text: String = underline(background(“Functional?”)) -
fun underline(text: String): String = … fun background(text: String): String
= … fun combine( ): { return } -
fun underline(text: String): String = … fun background(text: String): String
= … fun combine(f: (String) String, g: (String) String): { return } -
fun underline(text: String): String = … fun background(text: String): String
= … fun combine(f: (String) String, g: (String) String): { return { x g(f(x)) } } -
fun underline(text: String): String = … fun background(text: String): String
= … fun combine(f: (String) String, g: (String) String): (String) String { return { x g(f(x)) } } -
fun underline(text: String): String = … fun background(text: String): String
= … fun combine(f: (String) String, g: (String) String): (String) String { return { x g(f(x)) } } val h = combine( underline, background) val text = h(“Functional?”) -
fun underline(text: String): String = … fun background(text: String): String
= … fun combine(f: (String) String, g: (String) String): (String) String { return { x g(f(x)) } } -
fun underline(text: String): String = … fun background(text: String): String
= … fun ((String) String).combine(g: (String) String): (String) String { return { x g(this(x)) } } -
fun underline(text: String): String = … fun background(text: String): String
= … fun ((String) String).combine(g: (String) String): (String) String { return { x g(this(x)) } } val h = underline.combine( background) -
fun underline(text: String): String = … fun background(text: String): String
= … infix fun ((String) String).then(g: (String) String): (String) String { return { x g(this(x)) } } val h = underline.combine( background) -
fun underline(text: String): String = … fun background(text: String): String
= … infix fun ((String) String).then(g: (String) String): (String) String { return { x g(this(x)) } } val h = underline combine background -
fun underline(text: String): String = … fun background(text: String): String
= … infix fun ((String) String).then(g: (String) String): (String) String { return { x g(this(x)) } } val h = underline combine background val decoratedText = h(“Functional!?”) -
infix fun <P1, IP, R> ((P1) IP).combine(f: (IP)
R): (P1) R { return { p1: P1 f(this(p1)) } } -
infix fun <P1, IP, R> ((P1) IP).combine(f: (IP)
R): (P1) R { return { p1: P1 f(this(p1)) } }