Java design pattern of the enjoy Meta mode learning notes

Source: Internet
Author: User
Tags constant

The Flyweight pattern is used primarily to reduce the number of objects created to reduce memory footprint and improve performance. This type of design pattern is a structured pattern that provides a way to reduce the number of objects to improve the object structure required for application. The enjoy meta mode attempts to reuse an existing homogeneous object and create a new object if no matching object is found.

The implementation of a string in Java is a typical application of the use of a pattern, in Java, where a string exists in a constant pool of strings, Java ensures that a string constant has only one copy in a constant pool. Database connection pool is also a comparison of the telecommunications of the use of the mode of application, can be simply understood to initialize a certain number of database connections, when need to get the connection from the connection pool to obtain an available connection, when there is no available connection, then expand the connection pool number.


Flyweight in boxing competition the most lightweight, that is, "fly level" or "rainfall level", here choose to use the "" "The" "" "" mode of free translation, because this more reflect the meaning of the pattern. The pattern of the privilege is the structure pattern of the object. The privilege mode supports a large number of fine-grained objects efficiently and in a shared way.

Structure of the pattern of the privilege

The meta pattern uses a share to avoid the overhead of having a large number of identical content objects. The most common and intuitive of this overhead is the loss of memory. The key to sharing a shared object is to distinguish between the intrinsic state (Internal state) and the Outer Yun status (External states).

An intrinsic state is stored inside a privilege object and is not subject to change as the environment changes. Therefore, an element can have an intrinsic state and can be shared.

An external state is changed with the change of the environment and cannot be shared. The external state of the privilege object must be saved by the client and then passed into the inside of the object when it is needed, after the object is created. The external state can not affect the intrinsic state of the object, they are independent of each other.

The mode of the element can be divided into two forms, which are the pure element mode and the compound element mode.

Exclusive element mode
  
In the simple pattern of the privilege, all the objects of the privilege are shared.

In flyweight mode, factory patterns often occur in flyweight mode because of the variety of objects to be produced. The internal state of the Flyweight is shared, and Flyweight factory is responsible for maintaining an object storage pool (Flyweight pool) to store the internal state. Flyweight mode is a model that improves program efficiency and performance, and can greatly speed up the running of programs. There are many applications, for example:

First, define an abstract flyweight class:

Package Flyweight;
Public abstract class flyweight{
public abstract void operation ();
}

Implement a specific class:


Package Flyweight;
public class Concreteflyweight extends flyweight{
private string string;
Public concreteflyweight (String str) {
string = str;
}
public void operation ()
{
SYSTEM.OUT.PRINTLN ("Concrete---Flyweight:" + string);
}
}

Implement a factory method class:


Package Flyweight;
Import java.util.Hashtable;
public class flyweightfactory{
Private Hashtable flyweights = new Hashtable ()//----------------------------1
Public flyweightfactory () {}
Public Flyweight getflyweight (Object obj) {
Flyweight Flyweight = (Flyweight) flyweights.get (obj);//----------------2
if (flyweight = null) {//---------------------------------------------------3
Create a new Concreteflyweight
Flyweight = new Concreteflyweight ((String) obj);
Flyweights.put (obj, flyweight);//--------------------------------------5
}
Return flyweight;//---------------------------------------------------------6
}
public int getflyweightsize () {
return Flyweights.size ();
}
This factory method class is very critical, and here's a detailed explanation:
A hashtable is defined at 1 to store each object, and 2 to select the object to instantiate, return the object at 6, and if there is no object to select in Hashtable, the variable flyweight null. Produces a new flyweight stored in Hashtable and returns the object.
Finally look at the flyweight call:

Package Flyweight;
Import java.util.Hashtable;
public class flyweightpattern{
Flyweightfactory factory = new Flyweightfactory ();
Flyweight fly1;
Flyweight Fly2;
Flyweight Fly3;
Flyweight Fly4;
Flyweight fly5;
Flyweight Fly6;
/** *//** Creates a new instance of Flyweightpattern * *
Public Flyweightpattern () {
Fly1 = Factory.getflyweight ("Google");
Fly2 = Factory.getflyweight ("Qutr");
Fly3 = Factory.getflyweight ("Google");
Fly4 = Factory.getflyweight ("Google");
Fly5 = Factory.getflyweight ("Google");
Fly6 = Factory.getflyweight ("Google");
}
public void Showflyweight () {
Fly1.operation ();
Fly2.operation ();
Fly3.operation ();
Fly4.operation ();
Fly5.operation ();
Fly6.operation ();
int objSize = Factory.getflyweightsize ();
System.out.println ("objSize =" + objSize);
}
public static void Main (string[] args) {
System.out.println ("The FlyWeight pattern!");
Flyweightpattern fp = new Flyweightpattern ();
Fp.showflyweight ();
}
}

The following are the results of the operation:


Concrete---Flyweight:google
Concrete---FLYWEIGHT:QUTR
Concrete---Flyweight:google
Concrete---Flyweight:google
Concrete---Flyweight:google
Concrete---Flyweight:google
ObjSize = 2
We have defined 6 objects, 5 of which are the same, according to the definition of flyweight mode "Google" should share an object, in the actual number of objects we can see that the actual object is only 2.

Summarize:
The Flyweight mode is so important because it helps you save a lot of memory space in a complex system. In the Java language, the string type is the use of the element mode. A string object is a final type, and an object cannot be changed once it is created. In Java, where string constants exist in a constant pool, Java ensures that a string constant has only one copy in a constant pool. String a= "abc", where "abc" is a string constant.

Familiar with Java should know the following example:


String a = "Hello";
String b = "Hello";
if (a = = b)
System.out.println ("OK");
Else
System.out.println ("Error"); The output result is: OK. You can see if conditions are compared to the address of two A and B, which can be said to be memory space

Core summary of the objects that can be shared, that is, the same type of object returned is actually the same instance, and when a client asks for an object to be generated, the factory detects if there is an instance of the object, and if it does, it is created and saved if it does not exist, which is somewhat of a singleton pattern. Usually the factory class has a member variable of the collection type to hold the object, such as Hashtable,vector. In Java, the database connection pool, thread pool and so on is the use of the usage of the mode of application.

Here is an example of a combination of Factory mode and the use of the meta pattern:

Create the Shape interface and define a drawing method

Public interface Shape {
void Draw ();
}
Create the Circle class to implement the shape interface, define the related properties of the circle, and implement the drawing (draw) method.
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");
}
}
Import Java.util.HashMap;

Create a shapefactory factory class that stores objects through HashMap, obtains existing objects from the map by getcircle method, or generates new objects

public class Shapefactory {
private static final HashMap 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;
}
}
Randomly enter the color parameter to get the object from the factory
public class Flyweightpatterndemo {
private static final String colors[] = {"Red", "Green", "Blue", "white" and "Black"};

public static void Main (string[] args) {

for (int i = 0; i < ++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);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.