[Original-tutorial-serialization] "android big talk Design Pattern"-Design Pattern creation pattern Chapter 6: Prototype Pattern

Source: Internet
Author: User
<Big talk design model> description and copyright notice of this tutorial

L this document references and uses free images and content on the Internet, and is released in a free and open manner, hoping to contribute to the mobile Internet and the smart phone age! This document can be reproduced at will, but cannot be used for profit.

L if you have any questions or suggestions about this document, go to the official blog

Http://www.cnblogs.com/guoshiandroid/ (with the following contact information), we will carefully refer to your suggestions and modify this document as needed to benefit more developers!

L The latest and complete content of "big talk design mode" will be regularly updated on the official blog of guoshi studio. Please visit the blog of guoshi studio.

Http://www.cnblogs.com/guoshiandroid/get more updates.

Guoshi studio is a technical team dedicated to enterprise-level application development on the Android platform. It is committed to the best Android Application in China.ProgramDevelopment institutions provide the best Android enterprise application development training services.

Official contact information for Enterprise Training and Development Cooperation:

Tel: 18610086859

Email: hiheartfirst@gmail.com

QQ: 1740415547

Guoshi studio is better for you!

Prototype Words 

PrototypeUse Cases: 

Gg and mm often chat on QQ, but Gg's typing speed is slow, such as snail crawling. Every time Mm completes restoration or greetings in an instant, GG will try its best to quickly type, even so, it is still a bit difficult for mm, mm said that the reply information is so slow, obviously it is not dedicated, don't care about her. Ah, GG is also hard to argue, but there is indeed no way.

One day, GG wanted his friend K to talk about his difficulties. Kton laughed. Said: "silly, why don't you go to the Internet to collect some nasty words and theme related to your frequent conversations? Copy these things and save them in your computer or USB flash drive, in this way, you can borrow it for the next chat! ", "K is K. Why didn't I think of it ~ Wonderful ~ Wonderful! _ ^ "," but don't be so happy. These things should be modified as appropriate. Otherwise, if you make a wrong name, just wait for your mm to throw you to death ~" K added, "Well, that's right. Thank you, Brother K, for solving my problem." GG said happily.

This is where mm is used to chat with GG on the Internet. GG is dedicated to copying the prepared words and sending them to mm after slight modification. mm is almost beautiful...

Prototype mode explanation: 

Prototype pattern is an object creation mode. It creates an object instance by copying a prototype object. Instances created in prototype mode have the same initialization data as the prototype.

Specify the kinds of objects
To create using a prototypical instance, and create new objects by copying this
Prototype.

PrototypeUMLFigure:

The prototype model involves the following roles:

Client role: the client initiates a request to create an object.

Prototype role: it is usually implemented by a Java interface or Java Abstract class. In this way, the specifications are set up for the specific prototype.

Concrete prototype role: the specific object to be copied. This role implements the implementation method required by the abstract prototype role.

The UML diagram of the prototype mode is as follows:

In-depth analysis of prototype mode:

The working principle of the prototype mode is: by passing a prototype object to the object to be created, the object to be created is created by requesting the prototype object to copy themselves.

Java directly supports the prototype at the language level. We know that Java. Lang. object is the parent class of all classes and interfaces, while Java. Lang. Object provides a clone () method to support the prototype mode. Of course, if an object wants to be copied, it must declare that it has implemented the cloneable interface. If no declaration is made, clonenotsupportedexception will be thrown when the object is copied.

In Java. Lang. object, a protected
The object clone () method supports object cloning. Subclass can replicate all fields by default, or override clone () in subclass for convenience, customize your own replication behavior as needed.

Replication refers to shortest replication and deep replication. Shortest Replication refers to the basic data type and string type, and deep Replication refers to other reference types. For deep replication, each application also needs to declare the cloneable interface.

Analysis andCodeImplementation:

In the above application scenario, because Gg typing is too slow, it is often blamed by his girlfriend, so there is a way to copy the online chat and main chat topic content. In this way, each time Gg chats with MM, he just needs to copy the original words and modify them as appropriate, saving time and effort, and achieving excellent results ^_^, this is the benefit of the prototype of the Design Model O (cost _ cost) O ~

The UML Model diagram is as follows:

Create a hot talk class with very detailed comments in the class. I will not explain it here:

PackageCom. diermeng. designpattern. Prototype. impl;

Import
Java. util. arraylist;

ImportJava. util. List;

/*

* Hot Words

*/

Public ClassSweetwordImplementsCloneable {

// Sentence

PrivateString content;

// A collection of sentences

Private
List <string> contents;

 

/*

* Get a set of Hot Words

*/

PublicList <string>
Getcontents (){

ReturnContents;

}

/*

* Set a set of Hot Words

*/

Public Void
Setcontents (list <string> contents ){

This. Contents = contents;

}

 

 

/*

* Get your words

*/

PublicString
Getcontent (){

ReturnContent;

}

/*

* Set the words

*/

Public Void
Setcontent (string content ){

This. Content = content;

}

 

/*

* It overwrites the clone () method of the object class because list references are used for in-depth copying.

* @ See java. Lang. Object # clone ()

*/

PublicSweetword
Clone (){

Try{

// Create a new emotional object and copy basic attributes

Sweetword
Sweetword = (sweetword)Super. Clone ();

// Create a new chat set

List <string>
Newcontents =New
Arraylist <string> ();

// Add a new newcontents to the original object's meat and linen collection through the foreach Loop

For(String friend:This. Getcontents ()){

Newcontents. Add (friend );

}

// Set a new set of emotional words to a new object

Sweetword. setcontents (newcontents );

// Returns a new emotional object.

ReturnSweetword;

}Catch
(Clonenotsupportedexception e ){

E. printstacktrace ();

Return Null;

}

}

 

}

Finally, we create a test client:

Package
Com. diermeng. designpattern. Prototype. client;

 

Import
Java. util. arraylist;

ImportJava. util. List;

 

Import
Com. diermeng. designpattern. Prototype. impl. sweetword;

 

/*

* Test the client

*/

Public ClassPrototypeclient
{

Public Static VoidMain (string []
ARGs ){

 

// Create a new emotional object and set the corresponding attributes

Sweetword
Content1 =NewSweetword ();

List <string>
Contents =New
Arraylist <string> ();

Contents. Add ("Baby, I love you ");

Contents. Add ("you are my only ");

 

Content1.setcontents (contents );

// Copy content1

Sweetword
Content2 = content1.clone ();

// Enter the content of two objects respectively

System.Out. Println (content1.getcontents ());

System.Out. Println (content2.getcontents ());

 

// Add new content to the original emotional object and set the new content

Contents. Add ("You are my real girl ");

Content1.setcontents (contents );

 

// Output the new modified two emotional objects respectively

System.Out. Println (content1.getcontents ());

System.Out. Println (content2.getcontents ());

}

}

 

The output result is as follows:

[Baby, I love you, you are my only one]

[Baby, I love you, you are my only one]

[Baby, I love you, you are my only one, you are my real life girl]

[Baby, I love you, you are my only one]

 

Advantages and disadvantages of the prototype:

Advantages:

1. allow dynamic addition or reduction of product classes. Because the method for creating a product instance is internal to the product class, adding a new product has no impact on the entire structure.

2. A simplified structure is provided.

3. Ability to dynamically load new functions for an application.

4. Product classes do not need to have any pre-determined level structure, because the prototype applies to any level structure.

Disadvantages:

Each class must be equipped with a clone method, which is not very difficult for all new classes, but it is not easy for existing classes to implement the clone () method, in addition, when performing in-depth replication, you also need to write code that requires a certain amount of work.

Introduction to the practical application of the prototype:

Prototype objects are generally applicable to the following scenarios:

When creating an object, we not only want the created object to inherit the basic structure of its class, but also the data of the prototype object.

The modification of the target object does not affect the existing prototype objects (it can be completely independent from each other during deep cloning ).

Hide the details of the clone operation. In many cases, cloning an object involves data details of the class.

Tip:

Because when using the prototype mode, each class must have a clone method. If there is no good planning at the beginning of the class design, it may be very troublesome to think about cloning after a long time of use, especially when designing deep replication, this is because many factors are involved and the workload is huge.

Before making a copy to your girlfriend, you must fully check and make appropriate changes. If you do not make any mistakes, see the specific website. Otherwise, you are dead O (death _ death) o ha!


Related Article

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.