java-design mode (structural type)-"Enjoy meta mode"

Source: Internet
Author: User

1. Enjoy meta mode (Flyweight)

Definition: The main purpose of the enjoy meta-mode is to realize the sharing of objects , that is, the shared pool , which can reduce the overhead of memory when there are many objects in the system, usually used in conjunction with the Factory mode .

1.1 Factory

Factory: A pool is built in, and if it exists, it is taken out, otherwise the public class Factorypool {private hashtable<string,person> pool=new hashtable< is created in the join pool String,person> ();p ublic person Getperson (String name) {  //First out of pool, no one is created to be placed in the pool  p=pool.get (name);  if (p==null)  {  //create and join the pool  System.out.println ("Factory new Person:" +name);  P=new person (name);  Pool.put (name, p);  }  System.out.println ("Return a Person:" +name);  return p;}} Class Person{private string name;public person (string name) {This.name=name;}}

1.2 Testing

public class Test {public static void main (string[] args) {//TODO auto-generated method stub        factorypool  f=new Fa Ctorypool ();        Take person        P2=f.getperson ("HQ") from the factory;        Person P3=f.getperson ("cyx");        Person P1=f.getperson ("HQ");}}

1.3 Running Results

Factory new Person: HQ return a person: HQ factory New Person: Cyx Returns a person: Cyx returns a person: HQ

  

java-design mode (structural type)-"Enjoy meta mode"

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.