The Flyweight Pattern is mainly used to reduce the number of objects created to reduce memory footprint and improve performance. This type of design pattern is a structural pattern that provides a way to reduce the number of objects to improve the object structure required by the application. The meta-share pattern attempts to reuse existing objects of the same class, and if no match is found, new objects are created. We will demonstrate this pattern by creating five objects to draw 20 circles distributed in different locations. Since there are only five colors available, the color property is used to check existing Circle objects.

import java.util.HashSet; import java.util.Set; class FlyWeightPattern { public static void main(String[] args) { BikeFlyWeight bike1 = BikeFlyWeightFactory.getInstance().getBike(); bike1.ride("ZhangSan"); // bike1.back(); BikeFlyWeight bike2 = BikeFlyWeightFactory.getInstance().getBike(); bike2.ride("ZhaoSi"); bike2.back(); BikeFlyWeight bike3 = BikeFlyWeightFactory.getInstance().getBike(); bike3.ride("WangWu"); bike3.back(); System.out.println(bike1 == bike2); System.out.println(bike2 == bike3); }} abstract class BikeFlyWeight {// internal state protected Integer state = 0; Public void ride(String userName); public void ride(String userName); abstract void back(); public Integer getState() { return state; }} class MoBikeFlyWeight extends BikeFlyWeight {// Define a new internal state. public MoBikeFlyWeight(String bikeId) { this.bikeId = bikeId; } @Override void ride(String userName) { state = 1; System.out.println(userName + bikeId + "bikeId") ); } @Override void back() { state = 0; } } class BikeFlyWeightFactory { private static BikeFlyWeightFactory instance = new BikeFlyWeightFactory(); private Set<BikeFlyWeight> pool = new HashSet<>(); public static BikeFlyWeightFactory getInstance() { return instance; } private BikeFlyWeightFactory() { for (int i = 0; i < 2; I ++) {pool.add(new MoBikeFlyWeight(I + "")); } } public BikeFlyWeight getBike() { for (BikeFlyWeight bike : pool) { if (bike.getState() == 0) { return bike; } } return null; }}Copy the code