NOTE

Flyweight Pattern

Flyweight-pattern notes with UML and a Java example using a chess-object pool.

Software Architecture & Engineering1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Definition

Suitable when creating a large number of identical or similar objects, such as a thread pool.

2. UML

PlantUML 图表

3. Usage

3.1. Client

public class Client
{
    public static void main(String[] args)
    {
        Chess chess1 = ChessFactory.getChess("black");
        Chess chess2 = ChessFactory.getChess("black");

        // Same object
        System.out.println(chess1 == chess2);

        chess1.display(new Coordinate(10,20 ));

    }
}

3.2. Flyweight

public class Chess
{
    // Shared property
    protected String color;

    public Chess(String color)
    {
        this.color = color;
    }

    public String getColor()
    {
        return color;
    }

    public void setColor(String color)
    {
        this.color = color;
    }

    public void display(Coordinate coordinate)
    {

    }
}
public class ConcreateChess extends Chess
{
    public ConcreateChess(String color)
    {
        super(color);
    }

    @Override
    public void display(Coordinate coordinate)
    {
        System.out.println(this.color);
        System.out.println(coordinate);
    }

}
public class Coordinate
{
    // Unshared property
    private int x,y;

    public Coordinate(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString()
    {
        return "Coordinate{" + "x=" + x + ", y=" + y + '}';
    }

    public int getX()
    {
        return x;
    }

    public void setX(int x)
    {
        this.x = x;
    }

    public int getY()
    {
        return y;
    }

    public void setY(int y)
    {
        this.y = y;
    }
}

3.3. Factory

public class ChessFactory
{
    // Object pool
    private static Map<String, Chess> chessMap = new HashMap<>();

    public static Chess getChess(String color)
    {
        // Return it from the pool if present; otherwise create it and put it into the pool
        chessMap.putIfAbsent(color, new ConcreateChess(color));
        return chessMap.get(color);
    }
}

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub