欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 设计模式之原型模式

设计模式之原型模式

2025/6/6 0:22:27 来源:https://blog.csdn.net/m0_73431159/article/details/148309419  浏览:    关键词:设计模式之原型模式

原型模式(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'}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词