当前位置: 首页 > news >正文

【设计模式】【创建型5-5】【原型模式】

文章目录

  • 原型模式
    • 代码示例

原型模式

代码使用:spring框架里 bean的作用域
用途,以原型为模板,源源不断的创建(克隆 clone)对象。当直接创建对象的代价比较大时,则采用这种模式。

代码示例

public class Human implements Cloneable{private int age;private String name;private int sex;public Human(int age, String name, int sex) {this.age = age;this.name = name;this.sex = sex;}@Overrideprotected Human clone() {Human human = null;try {human = (Human) super.clone();} catch (CloneNotSupportedException e) {System.out.println(e);}return human;}
}class PrototypeMap {Map<String, Human> prototypeMap = new HashMap<>();public PrototypeMap() {// 初始化this.prototypeMap.put("Human", new Human(100, "666", 1));}public Object add(String k, Human v) {this.prototypeMap.put(k, v);return v;}public Human get(String k){Human o = this.prototypeMap.get(k);return o== null? o:o.clone();}
}
// 验证 原型模式 每次都返回出对象的克隆 且不同 虽然是浅克隆(深克隆 可以使用输入输出流 序列化反序列化)public static void main(String[] args) {PrototypeMap prototypeMap = new PrototypeMap();Human human1 = prototypeMap.get("Human");Human human2 = prototypeMap.get("Human");System.out.println(human1);System.out.println(System.identityHashCode(human1));System.out.println(human2);System.out.println(System.identityHashCode(human2));}
/*
Human{age=100, name='666', sex=1}
285377351
Human{age=100, name='666', sex=1}
344560770 */
http://www.lryc.cn/news/387013.html

相关文章:

  • 原子变量原理剖析
  • WebSocket走私实践(附赠LiveGBS监控系统未授权管理员密码重置)
  • CentOS 7 和 CentOS Stream 8 的主要区别
  • 基于go1.19的站点模板爬虫
  • (单机版)神魔大陆|v0.51.0|冰火荣耀
  • k8s自动补全工具和UI管理界面
  • 内网渗透:内网基础信息收集
  • cos符号链提示是什么?TOT呢?
  • docker-compose部署Flink及Dinky
  • 数字时代的文化革命:Facebook的社会影响
  • 66.前端接口调用返回400的错误
  • Hadoop 安装与伪分布的搭建
  • 网络安全:渗透测试思路.(面试)
  • 优化堆排序
  • vue3使用一些组件的方法
  • OceanBase 4.2.1 离线安装
  • ForkJoin
  • 实验2 色彩模式转换
  • AES加密算法及AES-CMAC原理白话版系统解析
  • 24年hvv前夕,微步也要收费了,情报共享会在今年结束么?
  • 【地理库 Turf.js】
  • springboot在线考试 LW +PPT+源码+讲解
  • JDBC中的事务及其ACID特性
  • Python | Leetcode Python题解之第204题计数质数
  • 【课程总结】Day10:卷积网络的基本组件
  • ModuleNotFoundError: No module named ‘_sysconfigdata_x86_64_conda_linux_gnu‘
  • 【物联网】室内定位技术及定位方式简介
  • Leetcode[反转链表]
  • 【差分数组】个人练习-Leetcode-2249. Count Lattice Points Inside a Circle
  • 【JavaEE】Cookie和Session详解