设计模式之原型模式

原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式之一。

原型模式包含以下几个主要角色:

  • 原型接口(Prototype Interface) :定义一个用于克隆自身的接口,通常包括一个 clone() 方法。

  • 具体原型类(Concrete Prototype) :实现原型接口的具体类,负责实际的克隆操作。这个类需要实现 clone() 方法,通常使用浅拷贝或深拷贝来复制自身。

  • 客户端(Client) :使用原型实例来创建新的对象。客户端调用原型对象的 clone() 方法来创建新的对象,而不是直接使用构造函数。

优点

  • 性能提高
  • 避免构造函数的约束

缺点

  • 配备克隆方法需要全面考虑类的功能,对已有类可能较难实现,特别是处理不支持串行化的间接对象或含有循环结构的引用时。

代码案例

复制代码
import java.util.UUID;  
  
public interface Prototype {  
    Object  clone();  
}  
  
/**  
 * 飞机类  
 */  
class Plane implements Prototype {  
    private Integer id;  
    private String type;  
  
    public Integer getId() {  
        return id;  
    }  
  
    public String getType() {  
        return type;  
    }  
  
    public Plane(){  
        id = (int) (Math.random() * 100 + 1);  
        type = UUID.randomUUID().toString();  
    }  
  
    public Plane(Plane plane){  
        this.id = plane.id;  
        this.type = plane.type;  
    }  
  
    @Override  
    public String toString() {  
        return "Plane{" +  
                "id=" + id +  
                ", type='" + type + '\'' +  
                '}';  
    }  
  
    @Override  
    public Object clone() {  
        return new Plane(this);  
    }  
}  
  
class Test{  
    public static void main(String[] args) {  
        Plane plane = new Plane();  
        System.out.println(plane);  
        Plane clone = (Plane) plane.clone();  
        System.out.println(clone);  
    }  
}

程序输出

复制代码
Plane{id=71, type='cc4e73ae-85c4-4735-a74d-d7bae0642724'}
Plane{id=71, type='cc4e73ae-85c4-4735-a74d-d7bae0642724'}
相关推荐
geovindu18 分钟前
rust: Template Method Pattern(续)
开发语言·后端·设计模式·rust·行为模式·板方法模式
博风1 小时前
17、设计模式应用举例:单件模式:多线程争冠军
设计模式
高晶14 小时前
无乘法器实现LC二阶滤波器:基于移位运算的快速算法与四种精度推导
算法·设计模式·程序员
高晶14 小时前
主从自动分配算法:平均值乘以设备数一半的选举基准值解析
算法·设计模式·程序员
延晗14 小时前
【从零开始 DeepSeek Harness 插件开发教程】二、一切皆插件:简单理解一下 Cordis 内核与 DSH 心智模型
设计模式·deepseek
高晶15 小时前
Android 通讯录应用开发实战:从零搭建 SQLite 数据持久化完整项目
android·设计模式·前端框架
日和雫21 小时前
封装、继承、多态 & 组合,为什么组合大于继承?
设计模式
代钦塔拉1 天前
【C++/Qt 进阶】设计模式系列(6):桥接模式——把“两个独立变化的维度“拆开
c++·qt·设计模式
haluhalu.1 天前
深入理解AIAgent(1.3)--- 设计模式
人工智能·python·设计模式·langchain
高晶2 天前
CANopen 在 BMS 系统中的 C 语言实战指南
设计模式·程序员