行业知识
设计模式之原型模式
2026-11-17 02:03:48
来源:互联网转载
原型模式(Prototype Pattern)
定义
通��复制现有对象来创建新对象,同时又保持了封装性。
通过复制现有对象来创建新的对象,而不是通过实例化新对象。这样可以提高对象创建的效率,尤其是在对象的创建过程比较昂贵或复杂的情况下
使用场景
- 当一个对象的构建代价过高时。例如某个对象里面的数据需要访问数据库才能拿到,而我们却要多次构建这样的对象。
- 当构建的多个对象,均需要处于某种原始状态时,就可以先构建一个拥有此状态的原型对象,其他对象基于原型对象来修改。
主要角色
- 抽象原型(Prototype): 定义用于复制自身的接口。通常包含一个克隆方法(Clone),该方法用于创建当前对象的副本。
- 具体原型(Concrete Prototype): 实现抽象原型接口,提供实际的克隆方法。客户端可以通过调用克隆方法来复制具体原型的实例。
类图
示例代码
public interface ProductPrototype { ProductPrototype copy();}@Datapublic class Product implements ProductPrototype { private String category; private String seller; private String brand; private String name; private double price; private String description; public Product(String category, String seller, String brand) { this.category = category; this.seller = seller; this.brand = brand; } @Override public Product copy() { return new Product(this.category, this.seller, this.brand); } public void showDetails() { System.out.println(JSON.toJSONString(this)); }}public class Client { public static void main(String[] args) { Product product = new Product("手机", "小米旗舰店", "小米"); Product note12 = product.copy(); note12.setName("红米Note12"); note12.setPrice(599.0); note12.showDetails(); Product pro13 = product.copy(); pro13.setName("小米Pro13"); pro13.setPrice(1499.0); pro13.showDetails(); }}工作中遇到场景
上一篇:台式电脑主机插座怎么连接