zoukankan      html  css  js  c++  java
  • Java原型模式

    原型模式

      原型模式也称克隆模式。原型模式jian ming zhi yi,就是先创造出一个原型,然后通过类似于Java中的clone方法,对对象的拷贝,克隆类似于new,但是不同于new。new创造出来的对象采用的是默认值。克隆出来的对象与原型对象相同,同时不会影响原型对象,然后在修改克隆出来的对象。

    实现

      继承Cloneable接口,重写clone方法。(此处的clone方法不是接口Cloneable中的抽象方法,而是obj中的方法)

    应用场景

      例:js中继承就是prototype就是采用原型模式。创建一个对象比较耗时时,采用原型模式。

    Demo

      

    public class Sheep implements Cloneable{
      private String name;
      private Date brithday;
      public String getName() {
        return name;
      }
      public void setName(String name) {
        this.name = name;
      }
      public Date getBrithday() {
        return brithday;
      }
      public void setBrithday(Date brithday) {
        this.brithday = brithday;
      }
      public Sheep() {
      }

      public Sheep(String name, Date brithday) {
        super();
        this.name = name;
        this.brithday = brithday;
      }

      @Override
      public String toString() {
        return "Sheep [name=" + name + ", brithday=" + brithday + "]";
      }
      @Override
      protected Object clone() throws CloneNotSupportedException {

      //此处的克隆只是简单的clone,原型模式中的对象中属性所引用的对象一旦修改,clone出来的对象的值也会随之改变,此处为浅复制
        Object obj = super.clone();
        return obj;
      }
    }

    public class Client {

      public static void main(String[] args) throws CloneNotSupportedException {
        Sheep s1 = new Sheep("多里",new Date());
        System.out.println(s1);
        Sheep s2 = (Sheep) s1.clone();
        System.out.println(s2);
      }
    }

      @Override
      protected Object clone() throws CloneNotSupportedException {

    //在复制的时候,同时对属性进行复制,通过此方式来进行深复制。
        Object obj = super.clone();
        Sheep s = (Sheep)obj;
        s.brithday = (Date) this.brithday.clone();
        return obj;
      }

  • 相关阅读:
    IOS开发中实现UITableView按照首字母将集合进行检索分组
    IOS开发中设置导航栏主题
    IOS中使用.xib文件封装一个自定义View
    IOS中将字典转成模型对象
    WindowsPhone8中LongListSelector的扩展解决其不能绑定SelectdeItem的问题
    WindowsPhone8.1 开发-- 二维码扫描
    tomcat 开机自启
    redis ubuntu 开机自启
    webStorm 中使用 supervisor 调试
    ubuntu 14.04 tab失效问题
  • 原文地址:https://www.cnblogs.com/zl96291/p/10125883.html
Copyright © 2011-2022 走看看