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?
Aucun commentaire:
Enregistrer un commentaire