PHP Flyweight Mode Usage Example

Source: Internet
Author: User

When we play, we will find that because there are only three races in the interstellar race, there are only dozens of units in the class.

Although the remaining blood of each individual soldier is different, the image animation of the same class is the same, even if different players are just different colors. For example, the crew of a human race.

And most players use only some of the most common classes, and often don't make all of them.

To solve the problem: the image of the class to share the animation.

Idea: We put the image animation of each class as an object and put it into memory sharing. Once a picture is used in this class, just take the shared image animation out and change the color.

Example of the Flyweight mode:

The code is as follows Copy Code

<?php

Machine Gun soldier Henry Yuan

Class Marineflyweight

{

Draw the image animation of the machine-gun, the parameter is the state, such as which player belongs to

Public Function Drawmarine ($state)

{

Draw the Machine-gun soldier

}

}

Enjoy Yuan Factory

Class Flyweightfactory

{

An array of privileges for storing multiple entities

Private $flyweights;

Ways to get the privilege

Public Function Getflyweight ($name)

{

if (!isset ($flyweights [$name]))

{

$flyweights [$name] = new $name. " Flyweight ";

}

return $flyweights [$name];

}

}

Initial Privilege Factory

$flyweightFactory = new Flyweightfactory ();

When we need to draw a machine-gun, pass an array of states, which contains the rest of the blood, and so on.

$marine = $flyweightFactory->getflyweight ("Marine");

$marine->drawmarine ($status);

?>

Usage Summary: The META mode can centralize the resources that need to be shared, manage them uniformly, and prevent repetitive consumption.

Implementation Summary: Need an exclusive plant to manage shared resources, such as the flyweightfactory above. The production of all the shared resources is given to the exclusive factory.

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.