In order to share an object, we may declare an interface and an intrinsic state through which flyweights can receive and act on it.
If you want to show a file system with folders to show the directories or subdirectories, you don't need to load all the files or directories at one loading time. You may show the upper level folders first. If the user clicks a folder, then load its subdirectories and files. The shared trigger is mouse-clicked. The composite pattern may be combined to define the flyweight system.
class Folder {
void draw(..) {}
}
class FolderFactory {
...
if (selected) {
return aFolder;
else
return aFile;
...
}
To show how to use flyweight to reduce object creation, we will make a program to draw 1000 circles with 6 different colors. Before we customize it to a flyweight design, it is coded as follows :
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Graphics g = panel.getGraphics();
for(int i=0; i < 1000; ++i) {
g.setColor(getRandomColor());
int r = getRandomR();
g.drawOval(getRandomX(), getRandomY(), r, r);
}
}
});
No comments:
Post a Comment
Note: only a member of this blog may post a comment.