This article summarizes Flyweight. According to wikipedia, "When you use equivalent instances in different places, you can save resources by reusing one instance." Reference: Flyweight pattern
** Main characters **
NO | name | role |
---|---|---|
1 | Flyweight class | The class you want to instantiate |
2 | FlyweightFactory class | Hold the state of the instantiated class |
If you want to represent a forest programmatically, you will probably generate a large number of tree instances. Generating a large amount consumes memory on the server, but it is a pattern that saves memory by reducing the number of instances at runtime. In Java, there was a method called String.intern as a tuning plan for memory saving, but I think that the idea (reusing objects with the same contents) is almost the same.
** Implement the pattern ** The purpose is simple and to reduce instantiation (new in source code). I will implement it with the example of wikipedia. A certain character string is defined character by character in char type, and if it is already defined, it will be reused, and if it is not defined, it will be generated.
** Flyweight class **
Stamp.java
class Stamp {
char type;
Stamp(char type){
this.type = type;
}
void print(){
System.out.print(this.type);
}
}
** FlyweightFactory class **
StampFactory.java
import java.util.Map;
import java.util.HashMap;
class StampFactory {
Map<Character, Stamp> pool;
StampFactory(){
this.pool = new HashMap<Character, Stamp>();
}
Stamp get(char type){
Stamp stamp = this.pool.get(type);
if(stamp == null) {
stamp = new Stamp(type);
this.pool.put(type, stamp);
}
return stamp;
}
}
** Execution class **
FlyweightTest.java
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
class FlyweightTest {
public static void main(String[] args) {
StampFactory factory = new StampFactory();
List<Stamp> stamps = new ArrayList<Stamp>();
stamps.add(factory.get('Ta'));
stamps.add(factory.get('Or'));
stamps.add(factory.get('I'));
stamps.add(factory.get('Ta'));
stamps.add(factory.get('Ke'));
stamps.add(factory.get('Ta'));
stamps.add(factory.get('hand'));
stamps.add(factory.get('Or'));
stamps.add(factory.get('Ke'));
stamps.add(factory.get('Ta'));
for(Stamp s : stamps){
s.print();
}
}
}
result
I was struck
If you put in a reusable process that reduces memory usage as much as possible, the overhead and overall performance part may be wrinkled, so you need to identify the points of each. However, in the case of Java language, in order to create one object, 2 bytes are consumed for characters (char type) and 4 bytes for integers (int type). If it is an environment that is accessed in parallel, even if it is temporary, the usage will increase several times, so I think it is an event (pattern) that you should be aware of.
Recommended Posts