Flyweight pattern is mainly used to reuse objects. This one of the structural pattern. We can understand this pattern by following example. Here we are using bikes with different type, color and cc.
1. Create interface as given below.
public interface Bike {
Bike getBike(String type);
void setColor(String color);
void setCc(int cc);
String getDetails();
}//Bike
2. Create class HondaBike as given below.
public class HondaBike implements Bike {
private int cc;
private String color, type;
public HondaBike(String type) {
this.type = type;
}//HondaBike
public Bike getBike(String type) {
return new HondaBike(type);
}//getBike
public void setColor(String color) {
this.color = color;
}//setColor
public void setCc(int cc) {
this.cc = cc;
}//setCc
public String getDetails() {
return "\nColor : " + color + "\tCC : " + cc + "\tType : " + type;
}//getDetails
}//class HondaBike
3. Create BikeGenerator as given below.
import java.util.HashMap;
public class BikeGenerator {
private HashMap<String, Bike> bikeStore = new HashMap<>();
public Bike getBike(String type) {
Bike bike = (Bike) bikeStore.get(type);
if(bike == null) {
bikeStore.put(type, new HondaBike(type));
System.out.print("\nGenerating new bike object with type : " + type);
}//if
else {
System.out.print("\nReturning existing object.");
}//else
return (Bike)bikeStore.get(type);
}//getBike
}//BikeGenerator
4. Now we can create our main class as given below.
public class Main {
public static void main(String args[]) {
BikeGenerator bg = new BikeGenerator();
Bike hondaSimple = bg.getBike("simple");
hondaSimple.setColor("Red");
hondaSimple.setCc(100);
System.out.print("\n" + hondaSimple.getDetails());
Bike hondaDelux = bg.getBike("delux");
hondaDelux.setColor("Red");
hondaDelux.setCc(150);
System.out.print("\n" + hondaDelux.getDetails());
Bike hondaGold = bg.getBike("gold");
hondaGold.setColor("Red");
hondaGold.setCc(350);
System.out.print("\n" + hondaGold.getDetails());
Bike hondaAgainSimple = bg.getBike("simple");
hondaAgainSimple.setColor("Black");
hondaAgainSimple.setCc(350);
System.out.print("\n" + hondaAgainSimple.getDetails());
}//PSVM
}//Main
And now you are ready to run example. Output will explain you waht we have achieved.