• 设计模式——原型模式(Prototype Pattern)


      原型模式:用原型实例制定创建对象的种类,并且通过拷贝这些原型创建新的对象。

      UML 图:

      原型类:

    package com.cnblog.clarck;
    
    /**
     * 原型类
     * 
     * @author clarck
     * 
     */
    public abstract class Prototype {
        private String mID;
    
        public Prototype(String id) {
            mID = id;
        }
    
        public String getID() {
            return mID;
        }
    
        public abstract Prototype Clone();
    }

      具体原型类:

    package com.cnblog.clarck;
    
    /**
     * 要想真正拥有克隆的能力,就需要实现Cloneable接口,重写clone方法。通过克隆方法得到的对象得到的是一个本地的副本
     * 
     * @author clarck
     * 
     */
    public class ConcreatePrototype1 extends Prototype implements Cloneable {
    
        public ConcreatePrototype1(String id) {
            super(id);
        }
    
        @Override
        public Prototype Clone() {
            Prototype protoType = null;
            try {
                protoType = (Prototype) clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
    
            return protoType;
        }
        
    }
    package com.cnblog.clarck;
    
    /**
     * 要想真正拥有克隆的能力,就需要实现Cloneable接口,重写clone方法。通过克隆方法得到的对象得到的是一个本地的副本
     * 
     * @author clarck
     * 
     */
    public class ConcreatePrototype2 extends Prototype implements Cloneable {
    
        public ConcreatePrototype2(String id) {
            super(id);
        }
    
        @Override
        public Prototype Clone() {
            Prototype protoType = null;
            try {
                protoType = (Prototype) clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
    
            return protoType;
        }
    
    }

      测试类:

    package com.cnblog.clarck;
    
    /**
     * 测试类
     * 
     * @author clarck
     * 
     */
    public class Client {
        public static void main(String[] args) {
            ConcreatePrototype1 p1 = new ConcreatePrototype1("clarck");
            ConcreatePrototype1 c1 = (ConcreatePrototype1) p1.Clone();
            
            String str = String.format("id:%s", c1.getID());
            System.out.println(str);
            
            ConcreatePrototype1 p2 = new ConcreatePrototype1("clarck2");
            ConcreatePrototype1 c2 = (ConcreatePrototype1) p2.Clone();
            
            String str2 = String.format("id:%s", c2.getID());
            System.out.println(str2);
        }
    }
  • 相关阅读:
    CRM
    eclipse 全局替换
    ps 泡泡
    SSH重新登录的问题
    又说oracle spatial 将Geometry转为gml
    其实你可以这样折腾java enum
    Sqlite 多线程入库
    Oracle spatial 将Geometry转换为gml字符串
    Oracle 关于WKT构造SDO_GEOMETRY的问题。
    Lucene之拉框查询
  • 原文地址:https://www.cnblogs.com/tanlon/p/3391173.html
Copyright © 2020-2023  润新知