As per the GOF definition for "Flyweight", reuse\share similar kind of objects to reduce the memory growth.
If this is the case, java string object does the same right by using string constant pool. Then can we say that Java String implements the Flyweight design pattern? If not, why?
Can we say that, Java String implements the Flyweight design pattern?
Not really. Or at best you can say that it can implement that pattern.
The string constant pool only contains String
objects that correspond to:
String.intern()
method.Normal Java String
objects are not created in the string pool. Instead, they are created in the normal heap, and only "put into the pool" by a call to intern()
. This is for good reason. If all strings were interned by default, it would increase GC overheads and/or the long-term memory footprint of a typical Java application.
(Note that Java 8 now has an optional string deduplication feature in the G1 collector which saves space by combining the char arrays of strings that are equal.)
Yes, Java's string pool is a good example of the flyweight pattern. As stated by the wikipedia article on the subject:
Another example [of this pattern] is string interning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With