23 Design Modes (7): Prototype mode __ design mode

Source: Internet
Author: User
Tags rand reserved

This article mainly introduces the prototype pattern in the design pattern.

Now the electronic bills are becoming more and more popular, such as your credit card, by the beginning of the month, the bank will send ane-mail to your mailbox, say how much you spend this month, when you spend, how many points, and so on, this is once a month, there is also a bank mail you must be very impressive: advertising letter, Now the credit card departments of the big banks are courting customers, e-mail is a cheap, fast way of communication, you use a paper advertising letter that high, such as our bank today launched a credit card lottery, through the electronic billing system can be sent to 6 million customers a night, why use the electronic billing system. Just find a junk mail tool and not solve the problem. It's a good idea, but it won't work in the financial industry. Because the bank sends this kind of mail to have the request:

Personalized service

The general bank requests the personalized service, sends in the past the mail always has some personal information, for example "XX", "xx lady" and so on.

Delivery success Rate

Mail delivery success rate has certain requirements, because the bulk of the sending mail will be the recipient mail server mistakenly recognized as spam, so in the mail header to add some forged data to circumvent the anti-spam engine mistakenly considered spam.

From these two aspects to consider the delivery of advertising letters is also an electronic billing system (electronic billing system generally includes: Bill analysis, billing generator, advertising letter management, send queue management, send machine, back letter processing, report management, and so on a child function, we today to consider the advertising letter this module how to develop. Since it is the advertising letter, must need a template, and then from the database to the customer's information one by one, put into the template to generate a complete message, and then throw it to the transmitter to send processing, class diagram as shown in Figure 13-1.

In the class diagram advtemplate is the template of advertising letters, usually from the database out, to generate a Bo or a dto, we use a static value to represent; Mail class is a mail class, sent by the sending machine is this class. Let's look at Advtemplate first, as shown in Listing 13-1.

Code Clear 13-1 Advertising template code

public class Advtemplate {  
    //advertising letter name  
    private String advsubject = "XX Bank National Day credit card lottery";   
    Advertising letter Content  
    Private String advcontext = "National Day Lottery Notice: As long as the card will send you 1 million." ....";   
    Get the name of the ad letter public  
    String Getadvsubject () {return  
        this.advsubject;  
    }  
    Get the content of the advertising letter public  
    String Getadvcontext () {return  
        this.advcontext;  
    }  

Code clear 13-2 Message Class code
public class Mail {//recipient private String receiver;   
    The message name is private String subject;   
    Appellation private String appellation;    
    The content of the message is private String contxt;  
    The tail of the mail, is generally added "XXX copyright" and other information private String tail;  
        Constructor public Mail (Advtemplate advtemplate) {this.contxt = Advtemplate.getadvcontext ();  
    This.subject = Advtemplate.getadvsubject ();  
    //The following is the Getter/setter method public String Getreceiver () {return receiver;  
    } public void Setreceiver (String receiver) {this.receiver = receiver;  
    Public String Getsubject () {return subject;  
    } public void Setsubject (String subject) {this.subject = subject;  
    Public String getappellation () {return appellation;  
    } public void Setappellation (String appellation) {this.appellation = appellation; } public String getContxt () {return contxt;  
    } public void Setcontxt (String contxt) {this.contxt = Contxt;  
    Public String GetTail () {return tail;  
    } public void Settail (String tail) {this.tail = tail;  }     
}


Code clear 13-3 Scene class

public class Client {//Number of bills sent, this value is obtained from the database private static int max_count = 6;  
        public static void Main (string[] args) {//simulate sending mail int i=0;  
        Define the template, which is to get mail mail = new mail (new Advtemplate ()) from the database;  
        Mail.settail ("XX Bank All rights reserved"); while (I<max_count) {//below is a different place for each message mail.setappellation (getrandstring (5) + "Mr. (female  
            ) ");   
            Mail.setreceiver (getrandstring (5) + "@" + getrandstring (8) + ". com");  
            Then send the message sendMail (mail);  
        i++; }//Send mail public static void SendMail (mail mail) {System.out.println ("title:" +mail.getsubject () + "/T recipient:" +mail.getreceiver () + "t ..... Sent successfully.  
    "); }//Get the specified length of the random string public static string getrandstring (int maxLength) {string Source = "Abcdefghijklm  
        NOPQRSKUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ ";  
      StringBuffer sb = new StringBuffer ();  Random rand = new Random ();  
        for (int i=0;i<maxlength;i++) {sb.append (Source.charat (Rand.nextint (Source.length ()));         
    return sb.tostring (); 

 }  
}
The results of the operation are shown below.

Title: XX Bank National day credit card lottery    recipient: fjQUm@ZnkyPSsL.com ...  . Sent successfully.  
Title: XX Bank National day credit card lottery    recipient: ZIKnC@NOKdloNM.com ...  . Sent successfully.  
Title: XX Bank National day credit card lottery    recipient: zNkMI@HpMMSZaz.com ...  . Sent successfully.  
Title: XX Bank National day credit card lottery    recipient: oMTFA@uBwkRjxa.com ...  . Sent successfully.  
Title: XX Bank National day credit card lottery    recipient: TquWT@TLLVNFja.com ...  . Sent successfully.  
Title: XX Bank National day credit card lottery    recipient: rkQbp@mfATHDQH.com  

Because it is a random number, each run has a difference, anyway, our electronic billing program is written out, can also be sent out normally. Let's take a closer look and see if there is a problem with the program. Looking here, this is a thread running, that is, you send is single-threaded, it takes 0.02 seconds to send out in accordance with an email (small enough, you have to go to the database to fetch data), 6 million emails need ... I calculate (break the finger calculation ...) , yes, is 33 hours, that is, a whole day is not finished, send today not finished, tomorrow's bill produced, accumulated accumulation, aroused party a pile of complaints, then how to do.

Good to do, the SendMail modified to multiple threads, but you only sendmail modified for multithreading or there are problems ah, you see Oh, the first mail object, put into thread 1 run, has not been sent out; Thread 2 also started, The recipient address and title of mail object mail are changed directly. Thread is not safe, OK, here, you will say that there are n many solutions, we do not say, we say one today, using a new model to solve this problem: the object copy function to solve this problem, the class diagram slightly modified, As shown in Figure 13-2.

With the addition of a cloneable interface (an interface from Java), mail implements this interface, and writes the Clone () method in the Mail class, we look at the changes in the Mail class, as shown in Listing 13-4.

Code clear 13-4 Revised message class

public class Mail implements cloneable{//recipient private String receiver;   
    The message name is private String subject;   
    Appellation private String appellation;    
    The content of the message is private String contxt;      
    The tail of the mail, is generally added "XXX copyright" and other information private String tail;  
        Constructor public Mail (Advtemplate advtemplate) {this.contxt = Advtemplate.getadvcontext ();  
    This.subject = Advtemplate.getadvsubject ();  
        @Override public Mail Clone () {mail mail =null;  
        try {mail = (mail) super.clone (); The catch (Clonenotsupportedexception e) {//TODO auto-generated catch block E.printstacktrace (  
        );  
    } return mail;  
    //The following is the Getter/setter method public String Getreceiver () {return receiver;  
    } public void Setreceiver (String receiver) {this.receiver = receiver; } public String GetsubJect () {return subject;  
    } public void Setsubject (String subject) {this.subject = subject;  
    Public String getappellation () {return appellation;  
    } public void Setappellation (String appellation) {this.appellation = appellation;  
    Public String Getcontxt () {return contxt;  
    } public void Setcontxt (String contxt) {this.contxt = Contxt;  
    Public String GetTail () {return tail;  
    } public void Settail (String tail) {this.tail = tail;  }     
}

Code Clear 13-5 Modified Scene class

public class Client {  
    //number of bills sent, this value is obtained from the database  
    private static int max_count = 6;  
      
    public static void Main (string[] args) {  
        //simulate sending mail  
        int i=0;  
        Define the template, which is to get  
        mail mail = new mail (new Advtemplate ()) from the data.  
        Mail.settail ("XX Bank All rights reserved");  
        while (I<max_count) {  
            //below is a different place for each message mail  
            clonemail = Mail.clone ();  
            Clonemail.setappellation (getrandstring (5) + "Mr. (Madam)");  
            Clonemail.setreceiver (getrandstring (5) + "@" + getrandstring (8) + ". com");              
            Then send the mail  
            sendMail (clonemail);  
            i++  
        }  
    }  
The operation result is unchanged, the same completes the electronic advertisement letter's sending function, moreover SendMail does not have the relation even if is multithreading. Pay attention to the method of Mail.clone () the bold character in the client class. Copy the object, create a new object, like the original object, and then modify the details of the data, such as setting the title, setting the recipient address, and so on. This pattern, which does not produce an object through the New keyword, but is implemented by an object copy is called a prototype pattern.

13.3 Application of Prototype model

Advantages of 13.3.1 Prototype model

A. Excellent performance

The prototype pattern is a copy of the memory binary stream, which is much better than a direct new object, especially when a large number of objects are generated in a loop, and the prototype model can reflect its advantages.

B. Escaping the constraints of a constructor

This is both its advantages and disadvantages, directly in the memory copy, the constructor will not be executed (see "prototype mode of attention"), the advantage is to reduce the constraints, the shortcomings are reduced constraints, double-edged sword, needs to be considered in practical applications.

Usage scenarios for 13.3.2 prototype mode

A. Resource optimization scenario

Class initialization needs to digest a lot of resources, including data, hardware resources, and so on.

B. Scenarios for performance and security requirements

Using new to produce an object that requires very cumbersome data preparation or access permissions, you can use the prototype pattern.

C. Scene of multiple modifier for an object

When an object needs to be accessible to other objects, and each caller may need to modify its value, consider using a prototype pattern to copy multiple objects for use by the caller.

In the actual project, the prototype pattern rarely appears alone, typically with the factory method pattern, creating an object through the Clone method, and then being supplied to the caller by the factory method. Prototype model has been merged with Java for Seamless, we can use it handy. The original text is reproduced in http://www.lxway.com/4058215002.htm


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.