Design Pattern Basic Tutorial

adplus-dvertising
Flyweight
Previous Home Next

The Flyweight is used to Make classes instance on the fly to improving performance efficiently, like individual icons or characters on the screen this means that we can declare an interface and also intrinsic state which flyweight will be received and perform operation on it. if we are want show a file system with the folder for visit the directory or subdirectory then not need to load the all file on one load time.

In this we can show the upper level folders first. because when the user or client click on the folder then firstly show the files or subdirectory.

Benefit and use of the Flyweight
  1. It is used icons to represent object.
  2. By the help of the classes An object extrinsic state can be shared.
  3. It is used Reduce the number of objects created, increase performance and decrease memory footprint.
  4. Increase runtime cost associated with finding or computing and transferring extrinsic data.
  5. Need to instantiate a large amount of small and fine-grained classes.

Example

package r4r;
import java.util.*;
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class flyweighttest extends JFrame {
private static final long serialVersionUID = 1L;
private static final Color colors[] = { Color.red, Color.blue,
Color.yellow, Color.orange,
Color.black,  Color.white };
private static final int WIDTH_ = 500,
HEIGHT = 500,
NUMBER_OF_CIRCLES = 1200;

Container contentPane = getContentPane();
JButton button1 = new JButton("Drawing Circle");
final JPanel  panel1  = new JPanel();

contentPane.add(panel1,BorderLayout.CENTER);
contentPane.add(button1,BorderLayout.SOUTH);
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);

button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Graphics g = panel1.getGraphics();

for(int i=0; i < NUMBER_OF_CIRCLES; ++i) {
g.setColor(getRandomColor());
int r = getRandomR();
g.drawOval(getRandomP(), getRandomQ(), r, r);
}
}
});
}

private int getRandomP() {
return (int)(Math.random()*WIDTH );
}
private int getRandomQ() {
return (int)(Math.random()*HEIGHT);
}
private int getRandomR() {
return (int)(Math.random()*(HEIGHT/5));
}
private Color getRandomColor() {
return colors[(int)(Math.random()*colors.length)];
}
public static void main(String[] args) {
flyweighttest test = new flyweighttest();
}   
}
Previous Home Next