设计模式之原型模式

原型模式(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'}
相关推荐
Doris_202312 小时前
代码格式化 使用oxfmt
设计模式·架构·前端框架
Doris_202313 小时前
说一说ESLint+Prettier生效的原理
前端·设计模式·架构
Pomelooooo14 小时前
把 git commit 这件事,彻底交给 AI ——一个工程化 /git-commit 命令的设计与落地
设计模式
invicinble15 小时前
设计模式(类的拓扑结构)(描述总纲)
设计模式·原型模式
invicinble18 小时前
设计模式(类的拓扑结构)(为什么会产生设计模式,以及什么是设计模式)
linux·服务器·设计模式
PersonalViolet20 小时前
模板方法模式实战:重构Agent工具审批,告别重复代码
设计模式·agent
老码观察20 小时前
设计模式实战解读(五):策略模式——干掉 if-else 的优雅方案
java·设计模式·策略模式
解决问题no解决代码问题21 小时前
设计模式分类介绍
java·开发语言·设计模式
烬羽21 小时前
从 Python List 到 LLM 接口:一条被忽视的 AI 入门捷径
设计模式
我爱cope1 天前
【Agent智能体8 | 反思设计模式-大语言模型反思机制的四个演进阶段】
人工智能·设计模式·语言模型