创建型设计模式之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...

相关推荐
怕浪猫18 小时前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane199421 小时前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19942 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..2 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
xiaofeiyang1502 天前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)3 天前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki4 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅664 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa4 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio
sarasuki4 天前
如何让 Agent 获取更多的能力?插件 / 技能系统
人工智能·设计模式·agent