zoukankan      html  css  js  c++  java
  • (二)原型模式-代码实现

    介绍

    概念:由对象来生成新的对象,而不是用类类型或其他方式.

    使用场景:需要对象克隆时

    特点:参数复制了,不用再初始化数据

    原型模式在C++等其他语言中运用较广,JAVA有Object的clone方法,所以使用起来比较简单

    首先假如Object中没有clone方法,怎么来实现原型模式?

    代码:

    首先创建对象实体

    //基类

    package note.com.bean;
    
    public abstract class Prototype {
        private String name = null;
        
        public abstract Prototype clone(Prototype p);
        
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }

    //子类

    package note.com.bean;
    
    public class Prototype1 extends Prototype {
        
        public Prototype clone(Prototype p){
            Prototype pp = new Prototype1();
            pp.setName(this.getName());
            return pp;
        }
    
    
    
    }

    //测试类

    package note.com.prototype;
    
    import note.com.bean.Prototype;
    import note.com.bean.Prototype1;
    
    public class PrototypeTest {
    
        public static void main(String[] args) {
            Prototype p1 = new Prototype1();
            p1.setName("1");
            System.out.println(p1);
            System.out.println(p1.getName());
            Prototype p11 = p1.clone(p1);
            System.out.println(p11);
            System.out.println(p11.getName());
        }
    }

    //结果

    note.com.bean.Prototype1@659e0bfd
    1
    note.com.bean.Prototype1@2a139a55
    1
    可得,对象已经是新的对象,但内容是相同的.

    使用JAVA的clone方法以后可以这么写,或者不重写clone方法,直接使用

    代码:

    //子类

    package note.com.bean;
    
    public class Prototype2 extends Prototype{
        
        public Prototype clone(Prototype p){
            Prototype pp = null;
            try {
                pp = (Prototype) this.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            return pp;
        }
        
        
    }

    注意:Object中的clone是浅克隆,如果想使用深克隆,就要自定义clone方法了(利用序列化实现深克隆属性)

    代码:

    //克隆方法:

     public  Object deepClone(Object o) throws IOException, ClassNotFoundException{
            //将对象写到流里
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(o);
            //从流里读回来
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            return ois.readObject();
        }
  • 相关阅读:
    Git 分支[转]
    监听键盘的输入事件[转]
    github for windows的初步使用
    限制一个form被同时打开的数量 Limite The Number of Forms Opened at the same time
    android内存检测工具
    面试 9.26 总结
    canvas path paint 的使用(游戏必备)
    android知识点
    android查缺补漏
    AIDL的使用
  • 原文地址:https://www.cnblogs.com/qinggege/p/5230157.html
Copyright © 2011-2022 走看看