【设计模式】原型模式

原型模式就像"细胞分裂"或"复印机":当你需要创建一个新对象时,不是通过 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
    }
}
相关推荐
Pasregret4 小时前
迭代器模式:统一数据遍历方式的设计模式
设计模式·迭代器模式
不当菜虚困4 小时前
JAVA设计模式——(二)组合模式
java·设计模式·组合模式
jack_xu5 小时前
经典大厂面试题——缓存穿透、缓存击穿、缓存雪崩
java·redis·后端
CHQIUU6 小时前
Java 设计模式心法之第4篇 - 单例 (Singleton) 的正确打开方式与避坑指南
java·单例模式·设计模式
碎梦归途6 小时前
23种设计模式-结构型模式之享元模式(Java版本)
java·开发语言·jvm·设计模式·享元模式
lozhyf6 小时前
Eureka搭建
java·spring cloud
Pasregret6 小时前
模板方法模式:定义算法骨架的设计模式
算法·设计模式·模板方法模式
幽络源小助理6 小时前
SpringBoot民宿管理系统开发实现
java·spring boot·springboot·民宿系统
东阳马生架构6 小时前
Nacos简介—1.Nacos使用简介
java
爱发飙的蜗牛7 小时前
springboot--web开发请求参数接收注解
java·spring boot·后端