创建型设计模式之Prototype(原型)

创建型设计模式之Prototype(原型)

摘要:

Prototype(原型)设计模式通过复制现有对象来创建新对象,避免重复初始化操作。该模式包含Prototype接口声明克隆方法、ConcretePrototype实现具体克隆逻辑,以及Client客户端调用克隆操作。示例代码展示了Product类实现Prototype接口,通过clone()方法复制对象属性。这种模式适用于创建成本较高的对象,能提高性能并简化对象创建过程。(149字)

1)意图

用原型实例是指定创建对象的种类,并且通过复制这些原型创建新的对象

2)结构

其中:

  • prototype声明一个复制自身的接口。
  • ConcretePrototype时效件一个复制的自身的操作。
  • Client 让一个原型复制自身从而创建一个新的对象。

3)适用性

Prototype 模式适用于:

  • 当一个系统应该独立于它的产品创建、构成和表示时。
  • 当要实例化的类是在运行时刻指定时,例如,通过动态装载。
  • 为了避免创建一个与产品类层次平行的工厂类层次时。
  • 当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们,可能比每次用合适的状态手工实例化该类更方便一些。
c 复制代码
public class PrototypeDemo {
    public static void main(String[] args) {
        Product product = new Product(1, "原型设计模式");
        System.out.println(product.getId() + "->" + product.getName());

        Product product1 = (Product) product.clone();
        System.out.println(product1.getId() + "->" + product1.getName());
    }
}

interface Prototype{
    Object clone();
}

class Product implements Prototype{
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Product() {
    }

    public Product(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public Object clone() {
        Product object = new Product();
        object.id = this.id;
        object.name = this.name;
        return object;
    }
}

喜欢我的文章记得点个在看,或者点赞,持续更新中ing...

相关推荐
范中勤13 小时前
技术文档:模型工厂 `llm_provider` / `llm_use` 分层设计
设计模式·langchain·架构设计·模型工厂·llm_provider
浅尝辄止;16 小时前
设计模式在HIS/LIS医疗系统中的完整实践指南(C#版)
开发语言·设计模式·c#
范中勤16 小时前
适配器模式(Adapter Pattern):原理、场景与 LLM 多厂商工程落地
设计模式·架构·langchain·适配器模式·多厂商
408高手1 天前
23种设计模式
设计模式
沫璃染墨1 天前
《Linux工程实践篇(二):线程池实战——从线程安全单例到完整源码实现》
linux·开发语言·c++·单例模式·设计模式·系统架构
sarasuki2 天前
MCP 为什么是一个协议而不是一个框架呢?
设计模式·agent·mcp
geovindu2 天前
rust: Borg Pattern(续)
开发语言·后端·设计模式·rust·博格模式
染指11102 天前
140.Agent-多Agent框架-Agent执行Skills流程
数据库·人工智能·设计模式·langchain·agents
sarasuki3 天前
Agent 是怎么做错误处理的呢?
人工智能·设计模式·agent
A1Book3 天前
从 0 设计历史专题资料汇编的 AI Agent 编排架构——六轮真实任务复盘
设计模式