您的位置:首页 > 娱乐 > 八卦 > 怎么做营销_安卓 开发_网店交易平台_seo引擎搜索入口

怎么做营销_安卓 开发_网店交易平台_seo引擎搜索入口

2025/4/19 13:01:24 来源:https://blog.csdn.net/liberalliushahe/article/details/146838767  浏览:    关键词:怎么做营销_安卓 开发_网店交易平台_seo引擎搜索入口
怎么做营销_安卓 开发_网店交易平台_seo引擎搜索入口

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

案例代码:基本实现

// 1. 实现 Cloneable 接口(标记可克隆)
class Shape implements Cloneable {private String type;public Shape(String type) {this.type = type;}// 2. 重写 clone() 方法(浅拷贝)@Overridepublic Shape clone() {try {return (Shape) super.clone();} catch (CloneNotSupportedException e) {return null;}}public String getType() { return type; }
}
// 使用示例
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}
}

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

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);}@Overridepublic 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")); // 输出: lightSystem.out.println(ConfigCache.getConfig("default").getSetting("theme")); // 输出: dark}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com