zoukankan      html  css  js  c++  java
  • 学习笔记——原型模式

    模拟实现:

     1 import java.util.Date;
     2 
     3 /**
     4 *原型模式: 通过一个已经创建好的对象来克隆出同样的其他对象(属性一样,通过实现Cloneable接口来实现),
     5 * 分为深拷贝和浅拷贝,要进行深拷贝,需要对原对象的引用类型属性也进行拷贝,或者用序列化的方式也可以实现深拷贝
     6 * 该模式有利于减少创建对象所耗费的时间,直接将内存中已有的对象进行拷贝,出去了new对象时的初始化,再赋值等一系列操作
     7  */
     8 public class Test {
     9     public static void main(String[] args) throws CloneNotSupportedException {
    10         Date date = new Date();
    11         User user = new User("张三", date);
    12         System.out.println(user.getName());
    13         System.out.println(user.getBirthday());
    14         System.out.println(user);
    15         System.out.println("===============");
    16 
    17         User user2 = (User)user.clone();
    18         date.setTime(5000000L);
    19         user2.setName("李四");
    20         System.out.println(user2.getName());
    21         System.out.println(user2.getBirthday());
    22         System.out.println(user2);
    23     }
    24 }
    View Code
     1 import java.util.Date;
     2 
     3 public class User implements Cloneable {
     4     public User(){
     5 
     6     }
     7 
     8     public User(String name, Date birthday) {
     9         this.name = name;
    10         this.birthday = birthday;
    11     }
    12 
    13     public Date getBirthday() {
    14         return birthday;
    15     }
    16 
    17     public void setBirthday(Date birthday) {
    18         this.birthday = birthday;
    19     }
    20 
    21     public String getName() {
    22         return name;
    23     }
    24 
    25     public void setName(String name) {
    26         this.name = name;
    27     }
    28 
    29     @Override
    30     public Object clone() throws CloneNotSupportedException {
    31         Date date = (Date)this.birthday.clone();
    32         User user = (User)super.clone();
    33         user.setBirthday(date);
    34         return user;
    35     }
    36 
    37     private String name;
    38     private Date birthday;
    39 }
    View Code
  • 相关阅读:
    js复习(一)
    Webform(文件上传)
    Webform(分页与组合查询配合使用)
    Webform(分页、组合查询)
    webform(内置对象)
    Webform(内置对象-Response与Redirect、QueryString传值、Repeater删改)
    Webform(Repeater控件)
    MDI窗体容器 权限设置
    进程和线程
    WinForm三级联动
  • 原文地址:https://www.cnblogs.com/Hr666/p/10384721.html
Copyright © 2011-2022 走看看