Design Patterns ----Prototype ( prototype ) Mode
GoF : Specifies the type of object to create with a prototype instance, and creates a new object by copying the prototypes.
Using Java Collections For example, ArrayList, HashMap, and so on must have had the experience of copy an object to another object, with the Clone () method probably used. Prototype mode plays such a role. The prototype mode allows one object to create another object without having to know any details about how to create it. (from the prototype of Banqiao-design pattern) Here we don't discuss deep copies and shallow copies. (Refer to "Thing in Java" Appendix A For detailed explanations)
In Java, because class object provides a clone () method, it implements the cloning of an object. So the implementation of the prototype pattern in Java is becoming very simple.
Prototype mode, in fact, is also one of the very simple patterns. We show the prototype pattern through an example:
Package Prototype;
Public abstract class Abstractmobile implements Cloneable
{
String Mobilename;
public void Setmobilename (String name)
{
Mobilename = name;
}//end setmobilename (...)
Public String Getmobilename ()
{
return mobilename;
}//end Getmobilename ()
The public Object Clone ()//implements the Clone method
{
object = null;
try{
Object = Super.clone ();
}catch (Clonenotsupportedexception cloneexception) {
System.err.println ("Abstratmobile is not cloneable");
Cloneexception.printstacktrace ();
}
return object;
}//end Clone ()
}//end Abstract class Abstractmobile
Package Prototype;
public class Mobile extends Abstractmobile
{
/** creates a new instance of Mobile * *
Public Mobile ()
{
Super.setmobilename ("NOKIA");
}//end Mobile
}//end class Mobile
Call to prototype mode:
/*
* Prototypepattern.java
*
* Created on March 28, 2006, 11:56
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
Package Prototype;
public class Prototypepattern
{
Abstractmobile mobile = new mobile ();
Abstractmobile newmobile = (Mobile) mobile.clone ();//Return object here requires type conversion
public void Showprototypepattern ()
{
Mobile.setmobilename ("NOKIA");
String Mobiletype = Mobile.getmobilename ();
System.out.println ("The new mobile is" + mobiletype);
}//end Showprototypepattern ()
public static void Main (string[] args)
{
System.out.println ("The Prototype pattern!");
Prototypepattern pp = new Prototypepattern ();
Pp.showprototypepattern ();
}//end Main (...)
}//class Prototypepattern
Here is a UML diagram, where the diagram is relatively simple. But it has been able to reflect the prototype model.
The prototype pattern in Java has almost become a call to the Clone () method. In fact, the Java Complex Class library provides a convenient condition for the implementation of design patterns. such as observer mode, Interator mode and so on.
trackback:http://tb.blog.csdn.net/trackback.aspx?postid=968297