【设计模式】原型模式

原型模式就像"细胞分裂"或"复印机":当你需要创建一个新对象时,不是通过 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
    }
}
相关推荐
cynicme2 小时前
力扣3318——计算子数组的 x-sum I(偷懒版)
java·算法·leetcode
青云交3 小时前
Java 大视界 -- Java 大数据在智能教育学习效果评估与教学质量改进实战
java·实时分析·生成式 ai·个性化教学·智能教育·学习效果评估·教学质量改进
崎岖Qiu3 小时前
【设计模式笔记17】:单例模式1-模式分析
java·笔记·单例模式·设计模式
Lei活在当下4 小时前
【现代 Android APP 架构】09. 聊一聊依赖注入在 Android 开发中的应用
java·架构·android jetpack
不穿格子的程序员4 小时前
从零开始刷算法-栈-括号匹配
java·开发语言·
lkbhua莱克瓦244 小时前
Java练习-正则表达式 1
java·笔记·正则表达式·github
yue0084 小时前
C#类继承
java·开发语言·c#
凯芸呢5 小时前
Java中的数组(续)
java·开发语言·数据结构·算法·青少年编程·排序算法·idea
竹竹零5 小时前
JacksonUtil--序列化与反序列化
java·开发语言·windows
钱多多_qdd5 小时前
基础篇:IoC(三):Bean实例化策略InstantiationStrategy
java·spring