蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测原型缓存克隆、浅拷贝共享引用陷阱、序列化深拷贝隔离与 CloneNotSupportedException

JAVAWindows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。ExplorePrototypePattern.java
ExplorePrototypePattern.java265 行
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class ExplorePrototypePattern {

    static abstract class Shape implements Cloneable {
        private String id;
        protected String type;

        abstract String draw();

        public String getType() {
            return type;
        }

        public String getId() {
            return id;
        }

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

        @Override
        public Object clone() {
            Object clone = null;
            try {
                clone = super.clone();
            } catch (CloneNotSupportedException e) {
                throw new AssertionError(e);
            }
            return clone;
        }
    }

    static class Rectangle extends Shape {
        public Rectangle() { type = "Rectangle"; }
        @Override String draw() { return "Inside Rectangle::draw() method."; }
    }

    static class Square extends Shape {
        public Square() { type = "Square"; }
        @Override String draw() { return "Inside Square::draw() method."; }
    }

    static class Circle extends Shape {
        public Circle() { type = "Circle"; }
        @Override String draw() { return "Inside Circle::draw() method."; }
    }

    static class ShapeCache {
        private static final Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>();

        public static Shape getShape(String shapeId) {
            Shape cachedShape = shapeMap.get(shapeId);
            return cachedShape == null ? null : (Shape) cachedShape.clone();
        }

        public static Shape peekCached(String shapeId) {
            return shapeMap.get(shapeId);
        }

        public static void loadCache() {
            shapeMap.clear();
            Circle circle = new Circle();
            circle.setId("1");
            shapeMap.put(circle.getId(), circle);

            Square square = new Square();
            square.setId("2");
            shapeMap.put(square.getId(), square);

            Rectangle rectangle = new Rectangle();
            rectangle.setId("3");
            shapeMap.put(rectangle.getId(), rectangle);
        }
    }

    static class DocumentTemplate implements Cloneable, Serializable {
        private static final long serialVersionUID = 1L;
        String title;
        List<String> tags;

        DocumentTemplate(String title, List<String> tags) {
            this.title = title;
            this.tags = new ArrayList<String>(tags);
        }

        public DocumentTemplate shallowCopy() throws CloneNotSupportedException {
            return (DocumentTemplate) super.clone();
        }

        public DocumentTemplate deepCopyBySerialization() throws Exception {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);
            oos.close();
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
            DocumentTemplate copy = (DocumentTemplate) ois.readObject();
            ois.close();
            return copy;
        }
    }

    static class NonCloneableBox {
        public Object tryClone() throws CloneNotSupportedException {
            return super.clone();
        }
    }

    public static void main(String[] args) throws Exception {
        List<Map<String, Object>> cases = new ArrayList<Map<String, Object>>();

        // Case 1: ShapeCache clone retrieval
        ShapeCache.loadCache();
        Shape c1 = ShapeCache.getShape("1");
        Shape c2 = ShapeCache.getShape("2");
        Shape c3 = ShapeCache.getShape("3");
        Shape c1Again = ShapeCache.getShape("1");

        Map<String, Object> cacheExp = new LinkedHashMap<String, Object>();
        cacheExp.put("lines", Arrays.asList("Shape : Circle", "Shape : Square", "Shape : Rectangle"));
        cacheExp.put("clone_distinct_from_cached", true);
        cacheExp.put("two_clones_distinct", true);

        Map<String, Object> cacheAct = new LinkedHashMap<String, Object>();
        cacheAct.put("lines", Arrays.asList(
            "Shape : " + c1.getType(),
            "Shape : " + c2.getType(),
            "Shape : " + c3.getType()
        ));
        cacheAct.put("clone_distinct_from_cached", c1 != ShapeCache.peekCached("1"));
        cacheAct.put("two_clones_distinct", c1 != c1Again);
        addCase(cases, "shape_cache_clone_retrieval",
            "验证 ShapeCache 基于 Cloneable 从缓存原型克隆出 Circle/Square/Rectangle,且每次克隆均产生新对象引用。",
            cacheExp,
            cacheAct);

        // Case 2: Shallow copy shared reference trap
        DocumentTemplate orig = new DocumentTemplate("Spec", Arrays.asList("v1", "draft"));
        DocumentTemplate shallow = orig.shallowCopy();
        shallow.tags.add("mutated");
        Map<String, Object> shallowExp = new LinkedHashMap<String, Object>();
        shallowExp.put("distinct_outer_object", true);
        shallowExp.put("shared_tags_list_ref", true);
        shallowExp.put("orig_tags_affected", Arrays.asList("v1", "draft", "mutated"));

        Map<String, Object> shallowAct = new LinkedHashMap<String, Object>();
        shallowAct.put("distinct_outer_object", orig != shallow);
        shallowAct.put("shared_tags_list_ref", orig.tags == shallow.tags);
        shallowAct.put("orig_tags_affected", orig.tags);
        addCase(cases, "shallow_copy_shared_reference_trap",
            "验证 Object.clone() 浅拷贝仅复制引用地址,修改克隆体的可变列表会同步影响原型对象。",
            shallowExp,
            shallowAct);

        // Case 3: Deep copy via Serializable stream isolation
        DocumentTemplate src = new DocumentTemplate("Report", Arrays.asList("core", "java8"));
        DocumentTemplate deep = src.deepCopyBySerialization();
        deep.tags.add("isolated-edit");
        deep.title = "Report-Copy";
        Map<String, Object> deepExp = new LinkedHashMap<String, Object>();
        deepExp.put("distinct_outer_object", true);
        deepExp.put("distinct_tags_list_ref", true);
        deepExp.put("src_tags_unchanged", Arrays.asList("core", "java8"));
        deepExp.put("deep_tags_updated", Arrays.asList("core", "java8", "isolated-edit"));

        Map<String, Object> deepAct = new LinkedHashMap<String, Object>();
        deepAct.put("distinct_outer_object", src != deep);
        deepAct.put("distinct_tags_list_ref", src.tags != deep.tags);
        deepAct.put("src_tags_unchanged", src.tags);
        deepAct.put("deep_tags_updated", deep.tags);
        addCase(cases, "deep_copy_via_serialization_isolation",
            "验证基于 Serializable 二进制流的深拷贝彻底隔离嵌套可变集合,互不影响。",
            deepExp,
            deepAct);

        // Case 4: Missing Cloneable throws CloneNotSupportedException
        boolean threw = false;
        try {
            new NonCloneableBox().tryClone();
        } catch (CloneNotSupportedException ex) {
            threw = true;
        }
        addCase(cases, "clone_without_cloneable_throws",
            "验证未实现 Cloneable 标记接口直接调用 super.clone() 会抛出 CloneNotSupportedException。",
            true,
            threw);

        Map<String, Object> root = new LinkedHashMap<String, Object>();
        root.put("runtime", "OpenJDK " + System.getProperty("java.version"));
        root.put("cases", cases);
        System.out.println(toJson(root));
    }

    private static void addCase(List<Map<String, Object>> cases, String name, String summary, Object expected, Object actual) {
        Map<String, Object> c = new LinkedHashMap<String, Object>();
        c.put("name", name);
        c.put("summary", summary);
        c.put("expected", expected);
        c.put("actual", actual);
        c.put("passed", Objects.equals(expected, actual));
        cases.add(c);
    }

    private static String toJson(Object obj) {
        if (obj == null) return "null";
        if (obj instanceof Boolean || obj instanceof Number) return obj.toString();
        if (obj instanceof String) return escapeString((String) obj);
        if (obj instanceof List<?>) {
            StringBuilder sb = new StringBuilder("[");
            List<?> list = (List<?>) obj;
            for (int i = 0; i < list.size(); i++) {
                if (i > 0) sb.append(",");
                sb.append(toJson(list.get(i)));
            }
            return sb.append("]").toString();
        }
        if (obj instanceof Map<?, ?>) {
            StringBuilder sb = new StringBuilder("{");
            boolean first = true;
            for (Map.Entry<?, ?> e : ((Map<?, ?>) obj).entrySet()) {
                if (!first) sb.append(",");
                first = false;
                sb.append(escapeString(String.valueOf(e.getKey()))).append(":").append(toJson(e.getValue()));
            }
            return sb.append("}").toString();
        }
        return escapeString(obj.toString());
    }

    private static String escapeString(String s) {
        StringBuilder sb = new StringBuilder("\"");
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            switch (ch) {
                case '"': sb.append("\\\""); break;
                case '\\': sb.append("\\\\"); break;
                case '\b': sb.append("\\b"); break;
                case '\f': sb.append("\\f"); break;
                case '\n': sb.append("\\n"); break;
                case '\r': sb.append("\\r"); break;
                case '\t': sb.append("\\t"); break;
                default:
                    if (ch < 0x20) {
                        sb.append(String.format("\\u%04x", (int) ch));
                    } else {
                        sb.append(ch);
                    }
            }
        }
        return sb.append("\"").toString();
    }
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。

入口文件:projects/design-pattern-prototype-pattern-lab/ExplorePrototypePattern.java

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 ExplorePrototypePattern.java,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:设计模式

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2710.zip

下载课程关联工程包:设计模式

课程关联工程包(登记关联36章) · 含当前章节或实例 · mbskycom202612a2686.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习