vimlesh yadav
01/20/2023, 7:47 AMCLOVIS
01/20/2023, 8:31 AMvimlesh yadav
01/20/2023, 8:32 AMJohn Matthews
01/30/2023, 2:32 PMCLOVIS
01/30/2023, 3:34 PMinterface Game {
val name: String
/** `true` if [move] is legal. */
fun canPlay(move: Move): Boolean
fun play(move: Move)
// some other methods…
}
class Game1 : Game {
override val name get() = "Game 1"
…
}
class Game2 : Game {
override val name get() = "Game 2"
…
}
What if you wanted to create variants of games where you can only play 3 moves? With regular inheritance you'd have to create a new class for each Game
subclass! With composition (implemented using delegation):
// Takes a Game implementation as parameter, and adds the maximum move count rule to it
class LimitedGame(private val game: Game, private val maxCount: Int) : Game by game {
private var currentCount = 0
override val canPlay(move: Move): Boolean {
if (currentCount >= maxCount)
return false
currentCount++
return game.canPlay(move)
}
// no need to implement the other methods, they are all delegated to the original game instance
}
over proven patternsComposition is a proven pattern. For example, it's item 16 in Effective Java, which doesn't even have composition at the language feature. It's also mentioned in the original Design Patterns book from 1994
John Matthews
01/30/2023, 3:38 PM