Design Mode - Create a schema of the prototype model (b)

The definition and characteristics of prototype models

  Prototype defined (the Prototype) mode are as follows: with an already created instance as a prototype to create a prototype of the same or similar new objects by copying this prototype object. Here, a prototypical instance specifies the kind of object to be created. Objects created in this way is very efficient, there is no need to know the details of object creation. For example, Windows operating system installation usually more time-consuming, if you copy a lot faster. Examples of replication in life very much, do not list them here.

Architecture and Implementation Mode Prototype

  Because  Java  provides a clone objects () method, it is implemented in Java prototype model is very simple.

1. Structure Model

  Prototype model consists of the following major role.

    1. Abstract prototype class: specifies the interface must implement specific prototype object.
    2. DETAILED class prototype: Prototype abstract class implement the clone () method, which is copied object.
    3. Access classes: using clone () method of class specific prototype to copy the new object.


  The structure shown in Figure 1.

           Prototype model of the structure of FIG.
                        1 prototype pattern configuration diagram of FIG.

2. Mode of realization

  Prototype model into a shallow clone and a deep clone clone, Java Object class provides the shallow clone of the clone () method, the prototype class can implement specific Cloneable interface object can be achieved shallow clone, here Cloneable interface is an abstract class prototype . Code is as follows:

  1. // specific prototype class
  2. class Realizetype implements Cloneable{
  3.   Realizetype () {
  4.     System the .out . Println ( "specific prototype created successfully!" );
  5.   }
  6.   public Object clone() throws CloneNotSupportedException{
  7.     System the .out . Println ( "specific prototype copy success!" );
  8.     return (Realizetype)super.clone();
  9.   }
  10. }
  11.   // prototype model of the test class
  12. public class PrototypeTest{
  13.   public static void main(String[] args)throws CloneNotSupportedException{
  14.     Realizetype obj1=new Realizetype();
  15.     Realizetype obj2=(Realizetype)obj1.clone();
  16.     System.out.println("obj1==obj2?"+(obj1==obj2));
  17.   }
  18. }


  Operating results of the program are as follows:

Specific prototyping success! 
Specific prototype replicate success! 
obj1 == obj2? false

Prototype Model Application Examples

  [Example 1] using a prototype simulation mode "Monkey" replicate itself.

    Analysis: Unplug the Monkey King monkey hair blowing gently becomes a lot Monkey King, which is actually used in the prototype model. Here Monkey class prototype SunWukong concrete classes, and Java in Cloneable interface is an abstract class prototype.

    Like Pig example described earlier, due to the display image Monkey King ( Click here to download Monkey the image of the program to be displayed ), so that the Monkey class defined panel JPanel subclass, which contains a label, for storing Monkey Image.

    Further, rewrite clone Cloneable interface () method for replicating new Monkey. Access classes can be copied a plurality of Monkey Monkey by calling clone () method, and displayed in a frame form JFrame. Figure 2 is a structural view.

         Monkey configuration diagram generator
                      FIG 2 is a configuration diagram generator Monkey


Code is as follows:

  1. import java.awt.*;
  2. import javax.swing.*;
  3. class SunWukong extends JPanel implements Cloneable{
  4.   private static final long serialVersionUID = 5543049531872119328L;
  5.   public SunWukong () {
  6.     JLabel l1=new JLabel(new ImageIcon("src/Wukong.jpg"));
  7.     this.add(l1);
  8.   }
  9.   public Object clone(){
  10.     SunWukong W = null ;
  11.     try{
  12.       W = (SunWukong ) Super . clone ();
  13.     }
  14.               catch(CloneNotSupportedException e){
  15.                             System the .out . Println ( "Wukong copy failed!" );
  16.               }
  17.               return w;
  18.        }
  19. }
  20. public class ProtoTypeWukong{
  21.   public static void main(String[] args){
  22.     The JFrame JF = new new the JFrame ( "Prototype Test Mode" );
  23.     jf.setLayout(new GridLayout(1,2));
  24.     Container contentPane=jf.getContentPane();
  25.     SunWukong OBJ1 = new new SunWukong ();
  26.     contentPane.add(obj1);
  27.     SunWukong obj2 = (SunWukong ) OBJ1 . Clone ();
  28.     contentPane.add(obj2);
  29.     jf . Pack ();
  30.     jf.setVisible(true);
  31.     jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  32.   }
  33. }


Running result of the program shown in Figure 3.

         Results Cloning Monkey's Run
                                Run Results FIG.'S 3 Cloning Monkey


  用原型模式除了可以生成相同的对象,还可以生成相似的对象,请看以下实例。

  【例2】用原型模式生成“三好学生”奖状。

    分析:同一学校的“三好学生”奖状除了获奖人姓名不同,其他都相同,属于相似对象的复制,同样可以用原型模式创建,然后再做简单修改就可以了。图 4 所示是三好学生奖状生成器的结构图。

           FIG configuration certificate generator
                          图4 奖状生成器的结构图


程序代码如下:

  1. public class ProtoTypeCitation{
  2.   public static void main(String[] args) throws CloneNotSupportedException{
  3.     citation obj1=new citation("张三","同学:在2016学年第一学期中表现优秀,被评为三好学生。","韶关学院");
  4.     obj1.display();
  5.     citation obj2=(citation) obj1.clone();
  6.     obj2.setName("李四");
  7.     obj2.display();
  8.   }
  9. }
  10. //奖状类
  11. class citation implements Cloneable{
  12.   String name;
  13.   String info;
  14.   String college;
  15.   citation(String name,String info,String college){
  16.     this.name=name;
  17.     this.info=info;
  18.     this.college=college;
  19.   System.out.println("奖状创建成功!");
  20.   }
  21.   void setName(String name){
  22.     this.name=name;
  23.   }
  24.   String getName(){
  25.     return(this.name);
  26.   }
  27.   void display(){
  28.     System.out.println(name+info+college);
  29.   }
  30.   public Object clone() throws CloneNotSupportedException{
  31.     System.out.println("奖状拷贝成功!");
  32.     return (citation)super.clone();
  33.   }
  34. }


  程序运行结果如下:

奖状创建成功!
张三同学:在2016学年第一学期中表现优秀,被评为三好学生。韶关学院
奖状拷贝成功!
李四同学:在2016学年第一学期中表现优秀,被评为三好学生。韶关学院

原型模式的应用场景

  原型模式通常适用于以下场景。

    • 对象之间相同或相似,即只是个别的几个属性不同的时候。
    • 对象的创建过程比较麻烦,但复制比较简单的时候。

原型模式的扩展

  原型模式可扩展为带原型管理器的原型模式,它在原型模式的基础上增加了一个原型管理器 PrototypeManager 类。该类用 HashMap 保存多个复制的原型,Client 类可以通过管理器的 get(String id) 方法从中获取复制的原型。其结构图如图 5 所示。
  

         Prototype pattern configuration diagram of a prototype band manager
                      图5 带原型管理器的原型模式的结构图


  【例3】用带原型管理器的原型模式来生成包含“圆”和“正方形”等图形的原型,并计算其面积。分析:本实例中由于存在不同的图形类,例如,“圆”和“正方形”,它们计算面积的方法不一样,所以需要用一个原型管理器来管理它们,图 6 所示是其结构图。
  

         FIG configuration pattern generator
                          图6 图形生成器的结构图


程序代码如下:

  1. import java.util.*;
  2. interface Shape extends Cloneable{
  3.   public Object clone(); //拷贝
  4.   public void countArea(); //计算面积
  5.   }
  6. class Circle implements Shape{
  7.   public Object clone(){
  8.     Circle w=null;
  9.     try{
  10.       w=(Circle)super.clone();
  11.     }
  12.     catch(CloneNotSupportedException e){
  13.       System.out.println("拷贝圆失败!");
  14.     }
  15.   return w;
  16.   }
  17. public void countArea(){
  18.   int r=0;
  19.   System.out.print("这是一个圆,请输入圆的半径:");
  20.   Scanner input=new Scanner(System.in);
  21.   r=input.nextInt();
  22.   System.out.println("该圆的面积="+3.1415*r*r+"\n");
  23.   }
  24. }
  25. class Square implements Shape{
  26.   public Object clone(){
  27.   Square b=null;
  28.   try{
  29.     b=(Square)super.clone();
  30.   }
  31.   catch(CloneNotSupportedException e){
  32.     System.out.println("拷贝正方形失败!");
  33.   }
  34.   return b;
  35. }
  36. public void countArea(){
  37.   int a=0;
  38.   System.out.print("这是一个正方形,请输入它的边长:");
  39.   Scanner input=new Scanner(System.in);
  40.   a=input.nextInt();
  41.   System.out.println("该正方形的面积="+a*a+"\n");
  42.   }
  43. }
  44. class ProtoTypeManager{
  45.   private HashMap<String, Shape>ht=new HashMap<String,Shape>();
  46.   public ProtoTypeManager(){
  47.   ht.put("Circle",new Circle());
  48.   ht.put("Square",new Square());
  49.   }
  50.   public void addshape(String key,Shape obj){
  51.   ht.put(key,obj);
  52.   }
  53.   public Shape getShape(String key){
  54.   Shape temp=ht.get(key);
  55.   return (Shape) temp.clone();
  56.   }
  57. }
  58. public class ProtoTypeShape{
  59.   public static void main(String[] args){
  60.     ProtoTypeManager pm=new ProtoTypeManager();
  61.     Shape obj1=(Circle)pm.getShape("Circle");
  62.     obj1.countArea();
  63.     Shape obj2=(Shape)pm.getShape("Square");
  64.     obj2.countArea();
  65.   }
  66. }


Run results are shown below:

This is a circular, enter the radius of the circle: 3 
area of the circle = 28.2735 

This is a square, enter its side length: 3 
area of the square = 9

Guess you like

Origin www.cnblogs.com/yuexiaoyun/p/11839064.html