zoukankan      html  css  js  c++  java
  • Prototype模式

    原型模式创建对象不调用原对象的构造函数,是直接copy原对象的
    浅克隆:对值类型的成员变量进行值的复制,对引用类型的成员变量只复制引用,不复制引用的对象.
    深克隆:对值类型的成员变量进行值的复制,对引用类型的成员变量也进行引用对象的复制.

    /**
    * Created by marcopan on 17/10/20.
    */
    public class Prototype implements Cloneable {
    private String name;

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public Object clone() {
    try {
    return super.clone();
    } catch (CloneNotSupportedException e) {
    e.printStackTrace();
    return null;
    }
    }
    }
    /**
    * Created by marcopan on 17/10/20.
    */
    public class NewPrototype implements Cloneable {
    private String id;
    private Prototype prototype;

    public String getId() {
    return id;
    }

    public void setId(String id) {
    this.id = id;
    }

    public Prototype getPrototype() {
    return prototype;
    }

    public void setPrototype(Prototype prototype) {
    this.prototype = prototype;
    }

    public Object clone() {
    NewPrototype ret = null;
    try {
    ret = (NewPrototype)super.clone();
    ret.prototype = (Prototype)this.prototype.clone();
    return ret;
    } catch (CloneNotSupportedException e) {
    e.printStackTrace();
    return null;
    }
    }

    public static void main(String[] args) {
    Prototype pro = new Prototype();
    pro.setName("original object");
    NewPrototype newObj = new NewPrototype();
    newObj.setId("test1");
    newObj.setPrototype(pro);

    NewPrototype clonObj = (NewPrototype)newObj.clone();
    clonObj.setId("testClone");
    clonObj.getPrototype().setName("changed object");

    System.out.println("original object id:" + newObj.getId());
    System.out.println("original object name:" + newObj.getPrototype().getName());

    System.out.println("cloned object id:" + clonObj.getId());
    System.out.println("cloned object name:" + clonObj.getPrototype().getName());
    }
    }
    运行结果:

    original object id:test1
    original object name:original object
    cloned object id:testClone
    cloned object name:changed object



  • 相关阅读:
    【ML-9-1】支持向量机--软硬间隔与支持向量机
    【ML-8】感知机算法-传统和对偶形式
    【ML-7】聚类算法--K-means和k-mediods/密度聚类/层次聚类
    【ML-7】聚类算法-实例代码
    【ML-6-2】集成学习-boosting(Adaboost和GBDT )
    【ML-6-1】集成学习-bagging(随机森林)
    【ML-5】决策树算法
    【ML-4】逻辑回归--用于分类
    【ML-3.1】梯度下降于牛顿法实例
    树状数组
  • 原文地址:https://www.cnblogs.com/panning/p/7701136.html
Copyright © 2011-2022 走看看