Add all 23 GoF design pattern implementations (2026-06-13)
This commit is contained in:
50
02-structural/flyweight/Main.java
Normal file
50
02-structural/flyweight/Main.java
Normal file
@@ -0,0 +1,50 @@
|
||||
package flyweight;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* Flyweight Design Pattern — Runnable Demo
|
||||
*
|
||||
* Creates 1000 trees of only 3 species. Without Flyweight: 1000 TreeType
|
||||
* objects. With Flyweight: 3 TreeType objects (one per species), shared.
|
||||
*
|
||||
* Run: javac flyweight/*.java && java flyweight.Main
|
||||
* Article: https://ankurm.com/flyweight-design-pattern-java/
|
||||
*/
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("=== Flyweight Design Pattern Demo ===\n");
|
||||
|
||||
List<Tree> forest = new ArrayList<>();
|
||||
Random rnd = new Random(42);
|
||||
|
||||
String[][] treeSpecs = {
|
||||
{"Oak", "dark-green", "rough-bark"},
|
||||
{"Pine", "blue-green", "needle-texture"},
|
||||
{"Birch","light-green","smooth-white-bark"}
|
||||
};
|
||||
|
||||
System.out.println("Creating 1,000 trees (only 3 TreeType objects should be created):");
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
String[] spec = treeSpecs[i % 3];
|
||||
TreeType type = TreeFactory.getTreeType(spec[0], spec[1], spec[2]);
|
||||
forest.add(new Tree(rnd.nextInt(800), rnd.nextInt(600), type));
|
||||
}
|
||||
|
||||
System.out.println("\nForest created. Drawing first 5 trees:");
|
||||
for (int i = 0; i < 5; i++) {
|
||||
forest.get(i).draw();
|
||||
}
|
||||
|
||||
System.out.println("\n--- Memory summary ---");
|
||||
System.out.println("Trees in forest : " + forest.size());
|
||||
System.out.println("Unique TreeType objects in pool: " + TreeFactory.getPoolSize());
|
||||
System.out.println("Without Flyweight : 1,000 TreeType objects");
|
||||
System.out.println("With Flyweight : " + TreeFactory.getPoolSize() + " TreeType objects shared");
|
||||
|
||||
System.out.println("\n=== Demo complete ===");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user