【设计模式】原型模式

原型模式就像"细胞分裂"或"复印机":当你需要创建一个新对象时,不是通过 new 重新构造,而是复制一个现有对象(原型),再修改细节。核心是 clone() 方法,类似"复制粘贴",能快速生成新对象,避免重复初始化开销。

案例代码:基本实现

java 复制代码
// 1. 实现 Cloneable 接口(标记可克隆)
class Shape implements Cloneable {
    private String type;
    
    public Shape(String type) {
        this.type = type;
    }

    // 2. 重写 clone() 方法(浅拷贝)
    @Override
    public Shape clone() {
        try {
            return (Shape) super.clone();
        } catch (CloneNotSupportedException e) {
            return null;
        }
    }

    public String getType() { return type; }
}
java 复制代码
// 使用示例
public class Main {
    public static void main(String[] args) {
        Shape circlePrototype = new Shape("Circle");
        
        // 克隆一个新对象(而非 new)
        Shape newCircle = circlePrototype.clone();
        System.out.println(newCircle.getType()); // 输出: Circle
    }
}

应用场景案例:缓存预加载配置

场景:系统启动时预加载配置模板,后续直接克隆配置,避免重复读取文件或数据库。

java 复制代码
import java.util.HashMap;
import java.util.Map;

// 配置类(支持深拷贝)
class AppConfig implements Cloneable {
    private Map<String, String> settings = new HashMap<>();

    public void setSetting(String key, String value) {
        settings.put(key, value);
    }

    public String getSetting(String key) {
        return settings.get(key);
    }

    @Override
    public AppConfig clone() {
        try {
            AppConfig copy = (AppConfig) super.clone();
            // 深拷贝:手动复制引用对象(如 Map)
            copy.settings = new HashMap<>(this.settings);
            return copy;
        } catch (CloneNotSupportedException e) {
            return null;
        }
    }
}

// 配置缓存池
class ConfigCache {
    private static Map<String, AppConfig> cache = new HashMap<>();

    static {
        // 初始化时加载默认配置
        AppConfig defaultConfig = new AppConfig();
        defaultConfig.setSetting("theme", "dark");
        defaultConfig.setSetting("font", "Arial");
        cache.put("default", defaultConfig);
    }

    public static AppConfig getConfig(String key) {
        return cache.get(key).clone(); // 返回克隆副本
    }
}

// 使用示例
public class Main {
    public static void main(String[] args) {
        // 获取配置克隆(避免修改影响缓存中的原型)
        AppConfig userConfig = ConfigCache.getConfig("default");
        userConfig.setSetting("theme", "light"); // 修改不影响原配置
        
        System.out.println(userConfig.getSetting("theme")); // 输出: light
        System.out.println(ConfigCache.getConfig("default").getSetting("theme")); // 输出: dark
    }
}
相关推荐
Han.miracle1 天前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
Le1Yu1 天前
分布式事务以及Seata(XA、AT模式)
java
寒山李白1 天前
关于Java项目构建/配置工具方式(Gradle-Groovy、Gradle-Kotlin、Maven)的区别于选择
java·kotlin·gradle·maven
无妄无望1 天前
docker学习(4)容器的生命周期与资源控制
java·学习·docker
MC丶科1 天前
【SpringBoot 快速上手实战系列】5 分钟用 Spring Boot 搭建一个用户管理系统(含前后端分离)!新手也能一次跑通!
java·vue.js·spring boot·后端
千码君20161 天前
React Native:从react的解构看编程众多语言中的解构
java·javascript·python·react native·react.js·解包·解构
夜白宋1 天前
【word多文档docx合并】
java·word
@yanyu6661 天前
idea中配置tomcat
java·mysql·tomcat
2501_916766541 天前
【项目部署】JavaWeb、MavenJavaWeb项目部署至 Tomcat 的实现方式
java·tomcat
RoboWizard1 天前
扩容刚需 金士顿新款Canvas Plus存储卡
java·spring·缓存·电脑·金士顿