Design Mode: Metadata mode and Design Mode
The Flyweight Pattern mode is mainly used to reduce the number of objects created to reduce memory usage and improve performance. This type of design pattern belongs to the schema pattern, which provides a way to reduce the number of objects and thus improve the object structure required by the application.
Intention
Use the sharing technology to effectively support a large number of fine-grained objects.
Implementation
We need to implement the following:
We have a graphic factory that can create multiple types of images, from which we need to obtain a large number of images
Create a factory
Public class Shape {private String shape; public Shape (String shape) {this. shape = shape;} public void draw () {System. out. println ("" + shape) ;}} public class ShapeFactroy {public Shape getShape (String s) {return new Shape (s );}}Add SAVE Function
Modify factory class
Public class ShapeFactroy {private HashMap
Map = new HashMap <> (); public Shape getShape (String s) {Shape shape = map. get (s); if (shape = null) {shape = new Shape (s); map. put (s, shape); System. out. println ("add" + shape);} return shape ;}}
Recycling
Public void main (String... args) {ShapeFactroy factroy = new ShapeFactroy (); factroy. getShape ("rectangle "). draw (); factroy. getShape ("square "). draw (); factroy. getShape ("circle "). draw (); factroy. getShape ("rectangle "). draw (); factroy. getShape ("rectangle "). draw (); factroy. getShape ("rectangle "). draw ();}Result
I/System. out: add the rectangle I/System. out: Draw the rectangle I/System. out: add the square I/System. out: draw a square I/System. out: add the circular I/System. out: Draw the circular I/System. out: Draw the rectangle I/System. out: Add a rectangle I/System. out: Draw a rectangle I/System. out: Draw a rectangle.