当前位置:网站首页>原型模式,咩咩乱叫
原型模式,咩咩乱叫
2022-06-26 05:36:00 【绿毛水怪12138】
什么是原型模式
原型模式(prototype):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象
UML图

示例性代码
@Override
public Prototype clone() {
Prototype clone=null;
try {
clone = (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
public class ConcretePrototype1 extends Prototype{
public ConcretePrototype1(String id) {
super(id);
}
@Override
public Prototype clone() {
return super.clone();
}
}
public class ConcretePrototype extends Prototype {
public ConcretePrototype(String id) {
super(id);
}
@Override
public Prototype clone() {
return super.clone();
}
}
值得注意的是在java中使用clone方法必须要实现Clonable接口,否则会抛出CloneNotSupportedException。
同时我们应该注意深拷贝和浅拷贝的区别,浅拷贝和深拷贝都会为我们开辟一个空间来存放对象,浅拷贝会复制基本数据类型的数据,对于对象数据类型的数据仅仅复制其指针,这种拷贝clone函数可以帮我们完成。深拷贝则需要我们自己开辟空间来存储对象数据类型。
以下内容来自此网站
原型模式的使用场景
如果你需要复制一些对象, 同时又希望代码独立于这些对象所属的具体类, 可以使用原型模式。
- 这一点考量通常出现在代码需要处理第三方代码通过接口传递过来的对象时。 即使不考虑代码耦合的情况, 你的代码也不能依赖这些对象所属的具体类, 因为你不知道它们的具体信息。
- 原型模式为客户端代码提供一个通用接口, 客户端代码可通过这一接口与所有实现了克隆的对象进行交互, 它也使得客户端代码与其所克隆的对象具体类独立开来。
如果子类的区别仅在于其对象的初始化方式, 那么你可以使用该模式来减少子类的数量。 别人创建这些子类的目的可能是为了创建特定类型的对象。
- 在原型模式中, 你可以使用一系列预生成的、 各种类型的对象作为原型。
客户端不必根据需求对子类进行实例化, 只需找到合适的原型并对其进行克隆即可。
- 在原型模式中, 你可以使用一系列预生成的、 各种类型的对象作为原型。
与其他设计模式之间的关系
边栏推荐
- Positioning setting horizontal and vertical center (multiple methods)
- FindControl的源代码
- 新的征程
- Wechat team sharing: technical decryption behind wechat's 100 million daily real-time audio and video chats
- cartographer_pose_graph_2d
- Life is so fragile
- [upsampling method opencv interpolation]
- Red team scoring method statistics
- 2021年OWASP-TOP10
- How to make your big file upload stable and fast?
猜你喜欢

Install the tp6.0 framework under windows, picture and text. Thinkphp6.0 installation tutorial

Leetcode114. 二叉树展开为链表

Replacing domestic image sources in openwrt for soft routing (take Alibaba cloud as an example)

redis探索之布隆过滤器

Fedora alicloud source

pytorch(网络模型训练)

Redis discovery bloom filter

【活动推荐】云原生、产业互联网、低代码、Web3、元宇宙……哪个是 2022 年架构热点?...

Official image acceleration

9 common classes
随机推荐
【PHP】PHP二维数组按照多个字段进行排序
How does P2P technology reduce the bandwidth of live video by 75%?
Pytorch中自己所定义(修改)的模型加载所需部分预训练模型参数并冻结
11 IO frame
The wechat team disclosed that the wechat interface is stuck with a super bug "15..." The context of
Cyclic displacement
Wechat team sharing: technical decryption behind wechat's 100 million daily real-time audio and video chats
cartographer_ pose_ graph_ 2d
Chapter 9 setting up structured logging (I)
C XX management system
[activity recommendation] cloud native, industrial Internet, low code, Web3, metauniverse... Which is the architecture hot spot in 2022
When was the autowiredannotationbeanpostprocessor instantiated?
About XXX management system (version C)
转帖——不要迷失在技术的海洋中
vscode config
skimage. morphology. medial_ axis
Consul服务注册与发现
睛天霹雳的消息
cartographer_backend_constraint
Leetcode513.找出树的左下角的值