design_model(11)flyweight

1.Enjoy element model

Pool technology is an important way to achieve, it can reduce the object created by the application, reduce the occupation of program memory, improve the performance of the program.

2.Example

public class Color {
    private  String  color;

	public String getColor() {
		return color;
	}

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

public class FlyWeight {
	private Map<String, Color> colors = new HashMap<>();

	public Color getColor(String str) {
		if (colors.containsKey(str)) {
			return colors.get(str);
		} else {
			Color color = new Color();
			colors.put(str, color);
			return color;
		}
	}
}

public class Client {
	public static void main(String[] args) {
		FlyWeight flyWeight = new FlyWeight();
		Color color = flyWeight.getColor("Red ");Color color2 = flyWeight.getColor ("red");System.out.println (color = = color2); / / true}}

 

Leave a Reply

Your email address will not be published. Required fields are marked *