added Factory Method pattern and corresponding tests
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -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.
|
||||
*
|
||||
*/
|
||||
|
||||
42
src/main/kotlin/design_patterns/Factory Method.kt
Normal file
42
src/main/kotlin/design_patterns/Factory Method.kt
Normal 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()
|
||||
}
|
||||
33
src/test/kotlin/design_patterns/FactoryMethodTest.kt
Normal file
33
src/test/kotlin/design_patterns/FactoryMethodTest.kt
Normal 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())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user