** Table of Contents ** There are various difficult things in the book, but in short, creating the same object multiple times is expensive in many ways, so create a Factory class and create an instance only once. Let's avoid it. That is the purpose of this pattern.
Use sharing to efficiently support a large number of small objects.
-Flyweight Abstract class of objects that need to generate a large number of identical instances ・ Concrete Flyweight Flyweight concrete class -Class that manages the UnsharedConcreteFlyweight Flyweight class Class that holds the Flyweight class as a child such as rows and columns -FlyweightFactory Class that generates the Flyweight class ・ Client user
Character class Class that manages one character
Character.kt
package flyweight
class Character(private val character: Char) {
fun print() {
print(character)
}
}
Character manufacturing class Create a factory class that instantiates and pools the character class. By pooling the objects once created in the class, the objects that have been created before will not be created again.
CharacterFactory.kt
package flyweight
//Make it a singleton object
object CharacterFactory {
val characterPool = HashMap<AllCharacter, Character>()
enum class AllCharacter(val value: Char) {
A('A'),
B('B'),
C('C'),
D('D'),
E('E'),
F('F'),
G('G'),
H('H'),
I('I'),
J('J'),
K('K'),
L('L'),
M('M'),
N('N'),
O('O'),
P('P'),
Q('Q'),
R('R'),
S('S'),
T('T'),
U('U'),
V('V'),
W('W'),
X('X'),
Y('Y'),
Z('Z')
}
fun getCharacterObject(characterType: AllCharacter): Character {
//If not created, pool the instance.
characterPool[characterType]?.let {
return it
} ?: run {
val char = Character(characterType.value)
characterPool[characterType] = char
return char
}
}
}
People who use letters Generate BANANA.
Client.kt
package flyweight
class Client {
init {
val characters = ArrayList<Character>()
// "BANANA"To generate
characters.add(CharacterFactory.getCharacterObject(CharacterFactory.AllCharacter.B))
characters.add(CharacterFactory.getCharacterObject(CharacterFactory.AllCharacter.A))
characters.add(CharacterFactory.getCharacterObject(CharacterFactory.AllCharacter.N))
characters.add(CharacterFactory.getCharacterObject(CharacterFactory.AllCharacter.A))
characters.add(CharacterFactory.getCharacterObject(CharacterFactory.AllCharacter.N))
characters.add(CharacterFactory.getCharacterObject(CharacterFactory.AllCharacter.A))
characters.forEach {
it.print()
}
}
}
[output]
BANANA
Recommended Posts