Latest web development tutorials

Flyweight

Flyweight (Flyweight Pattern) is mainly used to reduce the number of objects created to reduce memory usage and improve performance. This type of design patterns belong structural model, which provides a reduction in the number of objects to improve the structure of the object in a manner required by the application.

Flyweight try to reuse existing objects of the same, if the matching object is not found, a new object is created. We will draw 20 circles distributed in different locations by creating five objects to demonstrate this pattern. Since only five kinds of colors available, so the color attribute is used to check an existingCircleobject.

Introduction

Intent: Use sharing to support large numbers of fine-grained objects.

Mainly to solve: In a large number of objects, it may cause memory overflow, we put together a portion wherein the abstract, if you have the same service request directly back existing objects in memory, to avoid re-created.

When to use: 1, the system has a large number of objects.2, these objects consume lots of memory. 3, the state of most of these objects can be externalized. 4, a lot of these objects can be divided into groups according to the intrinsic state, when the object is removed from the outer Yun objects, each object can be set using an object instead. 5, the system does not depend on the identity of these objects, these objects are indistinguishable.

How to fix: Analyzing with a unique identification code, if there is in memory, the unique identification code of the identified objects is returned.

The key code: HashMap stored with these objects.

Application examples: 1, JAVA in String, if it returns, if not then create a string stored in the string buffer pool inside.2, the data pool database.

Advantages: significantly reduce the creation of objects, reducing the system's memory, so that efficiency is improved.

Disadvantages: increase in charge of the system, we need to separate the internal and external state status, and external state of nature are inherently should not change with the internal state of change, otherwise it will create chaos system.

Usage scenarios: 1, the system has a large number of similar objects.2, need to pool scene.

Note: 1, pay attention to the state of the external and internal division of the state, or it may cause thread-safety issues.2, the class must have a factory object to be controlled.

achieve

We will create aShapeinterface and implementation of the entity classesCircleShape interface. The next step is to define factory classesShapeFactory.

ShapeFactoryhave aCircleofHashMap,where the key colorCirclenamed object. Whenever a request is received, it will create a specific color circle.ShapeFactorycheck itsHashMapin the circle object, if foundCircleobjects, the object is returned, otherwise it will create a stored in the hashmap to prepare for subsequent use of the new object, and the object is returned to the client.

FlyWeightPatternDemo,our demo to get the class to useShapeFactoryShape object. It will transmit information(red / green / blue / black/ white) toShapeFactory,it needs to get the color of the object.

Flyweight pattern UML diagram

step 1

Create an interface.

Shape.java

public interface Shape {
   void draw ();
}

Step 2

Create entity class that implements the interface.

Circle.java

public class Circle implements Shape {
   private String color;
   private int x;
   private int y;
   private int radius;

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

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

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

   public void setRadius (int radius) {
      this.radius = radius;
   }

   @Override
   public void draw () {
      System.out.println ( "Circle: Draw () [Color:" + color 
         + ", X:" + x + ", y:" + y + ", radius:" + radius);
   }
}

Step 3

Create a factory to produce the object entity classes based on the given information.

ShapeFactory.java

import java.util.HashMap;

public class ShapeFactory {
   private static final HashMap <String, Shape> circleMap = new HashMap ();

   public static Shape getCircle (String color) {
      Circle circle = (Circle) circleMap.get (color);

      if (circle == null) {
         circle = new Circle (color);
         circleMap.put (color, circle);
         System.out.println ( "Creating circle of color:" + color);
      }
      return circle;
   }
}

Step 4

Use the factory to obtain an entity object of the class by passing the color information.

FlyweightPatternDemo.java

public class FlyweightPatternDemo {
   private static final String colors [] = 
      { "Red", "Green", "Blue", "White", "Black"};
   public static void main (String [] args) {

      for (int i = 0; i <20; ++ i) {
         Circle circle = 
            (Circle) ShapeFactory.getCircle (getRandomColor ());
         circle.setX (getRandomX ());
         circle.setY (getRandomY ());
         circle.setRadius (100);
         circle.draw ();
      }
   }
   private static String getRandomColor () {
      return colors [(int) (Math.random () * colors.length)];
   }
   private static int getRandomX () {
      return (int) (Math.random () * 100);
   }
   private static int getRandomY () {
      return (int) (Math.random () * 100);
   }
}

Step 5

Verify output.

Creating circle of color: Black
Circle: Draw () [Color: Black, x: 36, y: 71, radius: 100
Creating circle of color: Green
Circle: Draw () [Color: Green, x: 27, y: 27, radius: 100
Creating circle of color: White
Circle: Draw () [Color: White, x: 64, y: 10, radius: 100
Creating circle of color: Red
Circle: Draw () [Color: Red, x: 15, y: 44, radius: 100
Circle: Draw () [Color: Green, x: 19, y: 10, radius: 100
Circle: Draw () [Color: Green, x: 94, y: 32, radius: 100
Circle: Draw () [Color: White, x: 69, y: 98, radius: 100
Creating circle of color: Blue
Circle: Draw () [Color: Blue, x: 13, y: 4, radius: 100
Circle: Draw () [Color: Green, x: 21, y: 21, radius: 100
Circle: Draw () [Color: Blue, x: 55, y: 86, radius: 100
Circle: Draw () [Color: White, x: 90, y: 70, radius: 100
Circle: Draw () [Color: Green, x: 78, y: 3, radius: 100
Circle: Draw () [Color: Green, x: 64, y: 89, radius: 100
Circle: Draw () [Color: Blue, x: 3, y: 91, radius: 100
Circle: Draw () [Color: Blue, x: 62, y: 82, radius: 100
Circle: Draw () [Color: Green, x: 97, y: 61, radius: 100
Circle: Draw () [Color: Green, x: 86, y: 12, radius: 100
Circle: Draw () [Color: Green, x: 38, y: 93, radius: 100
Circle: Draw () [Color: Red, x: 76, y: 82, radius: 100
Circle: Draw () [Color: Blue, x: 95, y: 82, radius: 100