Design Pattern-prototype Pattern

Source: Internet
Author: User

Design Pattern-prototype Pattern

Original prototype: Specify the kinds of object to create using a prototypocal instance, and create new objects by copying this prototype. it means to use a prototype instance to specify the type of the object to be created, and create a new object by copying the prototype.

The prototype has three roles:

1. Customer role: it initiates a request to create an object.

2. Abstract prototype interface: Provides the interface required for a specific prototype, which usually implements the cloneable interface.

3. Specific prototype role: this role is a Copied object and implements an abstract prototype interface.

Class diagram of the prototype mode:

The code for each class is as follows:

Abstract prototype:

 

Package com. zz. prototpye;/*** abstract Prototype inherits the Cloneable interface, indicating that the class implemented by this interface can be copied * @ author txxs **/public interface Prototype extends Cloneable {// clone method, java built-in cloning mechanism to clone Prototype clone ();}

Specific prototype:

 

 

Package com. zz. prototpye;/*** implement object cloning * @ author txxs **/public class ConcretePrototype implements Prototype {@ Overridepublic Prototype clone () {try {return (Prototype) super. clone ();} catch (CloneNotSupportedException e) {e. printStackTrace (); return null ;}}}

Client:

 

 

Package com. zz. prototpye;/*** Client implementation * @ author txxs **/public class Client {public void operation (Prototype e) {Prototype p = e. clone ();}}

Use an example to describe how to send a promotion message to different people. First, declare a promotion message object and clone it to clone different message objects, set the cloned object to different users, send the message, and download the source code. Effect:

 

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.