CEN206 Object-Oriented Programming
Flyweight: Java Code Example - Client (Forest)
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class Forest extends JFrame {
private List<Tree> trees = new ArrayList<>();
public void plantTree(int x, int y, String name,
Color color, String texture) {
TreeType type = TreeFactory.getTreeType(
name, color, texture);
Tree tree = new Tree(x, y, type);
trees.add(tree);
}
@Override
public void paint(Graphics g) {
for (Tree tree : trees) {
tree.draw(g);
}
}
public static void main(String[] args) {
Forest forest = new Forest();
for (int i = 0; i < 1000000; i++) {
forest.plantTree(
(int) (Math.random() * 800),
(int) (Math.random() * 600),
"Summer Oak",
Color.GREEN,
"oak_texture");
}
forest.setSize(800, 600);
forest.setVisible(true);
}
}