1. Increase runtime cost associated with transferring, finding, or computing extrinsic data.
2. Reduce the number of objects created, decrease memory footprint and increase performance.
3. Need to instantiate a large amount of small and fine-grained classes.
4. An object extrinsic state can be shared by classes.
Example of Flyweight design pattern
In Java string class is designed with Flyweight design pattern. When you create a string constant, such constant is stored in a pool. When the second string is created, it will be checked to see if it has been created. If it is true, the second string instance will be picked up from the string pool instead of creating a new one.
String str1 = "test"; //
String str2 = "test"; // stored in the string pool.
String str3 = new String("test");
System.out.println(str1==str2); //true, as it shares the same memmory address
System.out.println(str1==str3); //false
Flyweight pattern uses the momory on fly. Another example would be like , you would like to display a folder structure with different subfolder which internally contains sub folders , files and so on. In this case we display only first level folder and display the subfolder on the fly when user clicks on the subfolder.Apply the same for subfolder too , hence objects are created on runtime increasing perfomance and reducing memory.
No comments:
Post a Comment