设计模式读书笔记之原型模式(Prototype)

来源:互联网 发布:javaweb角色权限源码 编辑:程序博客网 时间:2024/06/05 08:51

原型模式:通过克隆原型来创造新对象。

示例代码:

[java] view plain copy
  1. package designpattern.prototype;  
  2. public class Prototype implements Cloneable{  
  3.     private String name;  
  4.     public String getName() {  
  5.         return name;  
  6.     }  
  7.     public void setName(String name) {  
  8.         this.name = name;  
  9.     }  
  10.     public Prototype(String name){  
  11.         this.name = name;  
  12.     }  
  13.     public Prototype clone(){  
  14.         Prototype p = null;   
  15.         try {  
  16.             p = (Prototype) super.clone();  
  17.         } catch (CloneNotSupportedException e) {  
  18.             e.printStackTrace();  
  19.         }  
  20.         return p;  
  21.     }  
  22.       
  23. }  
  24.   
  25. //test case  
  26. package designpattern.prototype;  
  27. public class Test {  
  28.     public static void main(String[] args) {  
  29.         Prototype p = new Prototype("I am a prototype");  
  30.         Prototype p1 = p.clone();  
  31.         System.out.println(p1.getName());  
  32.     }  
  33. }  

其实在Java中原型模式其实就是Object.clone()的应用.

0 0
原创粉丝点击