Now I'm studying about Flyweight design pattern. I tried to find some examples through google, and this is what I found.
import java.awt.Color;
import java.awt.Graphics;
public interface Shape {
public void draw(Graphics g, int x, int y, int width, int height, Color color);
}
This is interface Shape.
import java.awt.Color;
import java.awt.Graphics;
public class Line implements Shape {...}
public class Oval implements Shape {...}
These two class implements Shape interface.
import java.util.HashMap;
public class ShapeFactory {
private static final HashMap<ShapeType, Shape> shapes = new HashMap<ShapeType, Shape>();
public static Shape getShape(ShapeType type) {
Shape shapeImpl = shapes.get(type);
if (shapeImpl == null) {
if (type.equals(ShapeType.OVAL_FILL)) {
shapeImpl = new Oval(true);
} else if (type.equals(ShapeType.OVAL_NOFILL)) {
shapeImpl = new Oval(false);
} else if (type.equals(ShapeType.LINE)) {
shapeImpl = new Line();
}
shapes.put(type, shapeImpl);
}
return shapeImpl;
}
public static enum ShapeType {
OVAL_FILL, OVAL_NOFILL, LINE;
}
}
Through this Factory class, Oval or Line class is made by the type. I understand it but I have one question about it. I learn that Static field or function can only use in Static class. However, in this example, static Hashmap and function is declared in non-static class ShapeFactory. I found other examples in google, but every examples are similar to this. I tried to do my own Flyweight model, but it does not work. Can anyone explain about this?

As they have mentioned above, the example you provide is not a Flyweight pattern. This pattern is helpful to reduce the memory amount used by an application. In the following example, we have a music app that will contain song and playlists.
Each song has an Id, the song name and the size.
A playlist contains a list of songs and the playlist name.
To see the behaviour of the application, I have created a Main class with 1000 songs and 300000 playlists with 80 songs per playlist. When the application starts, it will prompt the available memory and just before end will prompt the memory used. If you run this code, it will crash due to memory limitation.
To avoid this memory limitation, we can use the flightweight pattern. To implement this pattern we can add a Map to store the songs added to a playlist. If a song was never added to a playlist it will be added to the map. At the end of the execution, the total memory used for the application should be arround 2.6 GB
I will add an implementation using SongFactory class that will allow to enable or disable the Flyweight functionallity with a boolean
I hope this will help you to understand better the Flyweight pattern