设计模式(三)——原型模式

一、引子 1、克隆人的问题

  问题:有一个人叫张三,姓名:张三,年龄:18,身高:178。如何创建和张三属性完全相同的10个人呢?
  代码示例:

1 public class Main { 2 3 public static void main(String[] args) { 4 Person p0 = new Person("张三", 18, 178); 5 6 Person p1 = new Person(p0.getName(), p0.getAge(), p0.getHeight()); 7 Person p2 = new Person(p0.getName(), p0.getAge(), p0.getHeight()); 8 Person p3 = new Person(p0.getName(), p0.getAge(), p0.getHeight()); 9 Person p4 = new Person(p0.getName(), p0.getAge(), p0.getHeight()); 10 Person p5 = new Person(p0.getName(), p0.getAge(), p0.getHeight()); 11 Person p6 = new Person(p0.getName(), p0.getAge(), p0.getHeight()); 12 Person p7 = new Person(p0.getName(), p0.getAge(), p0.getHeight()); 13 Person p8 = new Person(p0.getName(), p0.getAge(), p0.getHeight()); 14 Person p9 = new Person(p0.getName(), p0.getAge(), p0.getHeight()); 15 Person p10 = new Person(p0.getName(), p0.getAge(), p0.getHeight()); 16 17 System.out.println(JSON.toJSONString(p0)); 18 } 19 } 20 21 class Person { 22 private String name; 23 private int age; 24 private int height; 25 // getter & setter 26 // 有参数、无参构造器 27 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzsfgj.html