In this example we will show how to implement Flyweight Pattern in Java.
Source Code
package com.beginner.examples;
import java.util.*;
//chess
abstract class Chess {
public abstract String getSize();
public void display() {
System.out.println("Size:" + this.getSize());
}
}
//big chess
class BigChess extends Chess {
public String getSize() {
return "big";
}
}
//small chess
class SmallChess extends Chess {
public String getSize() {
return "small";
}
}
//flyweight factory
class FlyWeightFactory {
private static FlyWeightFactory instance = new FlyWeightFactory();
private static Hashtable h; //flyweight pool
private FlyWeightFactory() {
h = new Hashtable();
Chess big, small;
big = new BigChess();
h.put("b",big);
small = new SmallChess();
h.put("s",small);
}
public static FlyWeightFactory getInstance() {
return instance;
}
public static Chess getChess(String color) {
return (Chess)h.get(color);
}
}
public class FlyweightExample {
public static void main(String args[]) {
Chess big1, big2, small1, small2;
FlyWeightFactory factory = FlyWeightFactory.getInstance();
big1 = factory.getChess("b");
big2 = factory.getChess("b");
small1 = factory.getChess("s");
small2 = factory.getChess("s");
big1.display();
big2.display();
small1.display();
small2.display();
}
}
Output:
Size:big
Size:big
Size:small
Size:small