Categories
Algorithms & Design Design Pattern

Fly Weight Pattern

Square.java

public class Square {
	private String color;
	public Square(String color) {
		this.color=color;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public String toString(){
		return "square with color:"+color;
	}
}

SquareFactory.java

import java.util.HashMap;
import java.util.Map;

public class SquareFactory {

	public SquareFactory() {
		// TODO Auto-generated constructor stub
	}

	private static Map objectMap = new HashMap();
	
	public static Square getSquare(String color){
		Square square = objectMap.get(color);
		if(square==null){
			System.out.println("creating new square with color:"+color);
			square = new Square(color);
			objectMap.put(color, square);
		}else {
			System.out.println("returning existing cached circle");
		}
		return square;
	}
}

FlyWeightPatternDemo.java

public class FlyWeightPatternDemo {

	public FlyWeightPatternDemo() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		SquareFactory factory = new SquareFactory();
		
		//get me red square
		System.out.println("requested red square : "+factory.getSquare("red"));
		System.out.println("--------------------------------------------------");
		
		System.out.println("requested red square : "+factory.getSquare("yellow"));
		System.out.println("--------------------------------------------------");

		System.out.println("requested red square : "+factory.getSquare("green"));
		System.out.println("--------------------------------------------------");
		
		System.out.println("requested red square : "+factory.getSquare("red"));
		System.out.println("--------------------------------------------------");

	}

}

Output

Leave a comment

Design a site like this with WordPress.com
Get started