zoukankan      html  css  js  c++  java
  • java设计模式-原型(prototype)

    有时候创建对象是需要耗费很多资源,但是每个对象之间又有大量的重复。我们可以选择在创建好一个对象后,以之作为模板克隆出其他对象,稍作修改,即可用于其他地方。

     需要实现Cloneable接口,重写clone()方法。其实就是调用的Object类的clone()方法。

    克隆对象只是复制了原对象的数据,每个对象还是独立的,他们的内存地址不同。

    /**
     * Created by wangbin10 on 2018/5/18.
     */
    public class Prototype2 implements Cloneable,Serializable {
        private static final long serialVersionUID = 2L;
        private String name;
        private Integer payAmount;
        private String msg;
    
        public Prototype2() {
        }
    
        public Prototype2(String name, Integer payAmount, String msg) {
            this.name = name;
            this.payAmount = payAmount;
            this.msg = msg;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Integer getPayAmount() {
            return payAmount;
        }
    
        public void setPayAmount(Integer payAmount) {
            this.payAmount = payAmount;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    
        public Prototype2 clone() throws CloneNotSupportedException {
            Prototype2 clone = (Prototype2) super.clone();
            return clone;
        }
    }
    /**
     * Created by wangbin10 on 2018/5/18.
     */
    public class PTest {
        public static void main(String[] args) throws CloneNotSupportedException {
            Prototype2 p1=new Prototype2("zhangsan",23,"hello!welcome to beijing!");
            System.out.println(p1.getName()+p1.getPayAmount()+p1.getMsg());
            Prototype2 p2 = p1.clone();
            p2.setName("lisi");
            p2.setPayAmount(24);
            System.out.println(p2.getName()+p2.getPayAmount()+p2.getMsg());
            System.out.println("============================");
            System.out.println(p1.getName()+p1.getPayAmount()+p1.getMsg());
    
        }
    }
  • 相关阅读:
    JQuery
    a:hover伪类在ios移动端浏览器内无效的解决方法
    git rebase 过程中遇到冲突该怎么解决?
    git
    vue单文件中scoped样式如何穿透?
    微信小程序-怎么获取当前页面的url
    es6 class 中 constructor 方法 和 super
    如何将svg图标快速转换成字体图标?
    JavaWeb三大组件之一Filter知识总结
    Session的引入以及Cookie的不足
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/9056130.html
Copyright © 2011-2022 走看看