added Factory Method pattern and corresponding tests

This commit is contained in:
Dmitry
2022-02-15 13:06:04 +07:00
parent bfff076bf0
commit 5353e0998c
8 changed files with 77 additions and 0 deletions

View File

@ -5,7 +5,9 @@ import java.util.*
/**
*
* An abstract factory is a generative design pattern that allows
*
* you to create families of related objects without being tied to
*
* the specific classes of objects you create.
*
*/

View File

@ -0,0 +1,42 @@
package design_patterns
/**
*
* A factory method is a generic design pattern that defines
*
* a common interface for creating objects in a superclass,
*
* allowing subclasses to change the type of objects they create.
*
*/
abstract class Pony4
class EarthPony4 : Pony4()
class Pegasus4 : Pony4()
class Unicorn4 : Pony4()
abstract class Place {
private var numberOfPonies = 0
abstract fun pony() : Pony4
fun newPony() : Pony4 {
numberOfPonies++
return pony()
}
fun count() = numberOfPonies
}
class Cloudsdale : Place() {
override fun pony() = Pegasus4()
}
class Canterlot : Place() {
override fun pony() = Unicorn4()
}
class Ponyville : Place() {
override fun pony() = EarthPony4()
}

View File

@ -0,0 +1,33 @@
package design_patterns
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsInstanceOf.instanceOf
import org.junit.Test
import org.junit.jupiter.api.Assertions.assertEquals
class FactoryMethodTest {
@Test
fun test_match_objects() {
val ponyville = Ponyville()
val earthPony = ponyville.newPony()
assertThat(earthPony, instanceOf(EarthPony4::class.java))
val canterlot = Canterlot()
val unicorn = canterlot.newPony()
assertThat(unicorn, instanceOf(Unicorn4::class.java))
}
@Test
fun test_count() {
val cloudsDale = Cloudsdale()
cloudsDale.newPony()
cloudsDale.newPony()
cloudsDale.newPony()
assertEquals(3, cloudsDale.count())
}
}