`
d02540315
  • 浏览: 32548 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
社区版块
存档分类
最新评论

Using the Prototype pattern to clone objects

阅读更多
Prototype pattern is one of the creational patterns that concentrate on duplicating objects if needed. Assuming that we are in process of creating a template. Most of the times, we copy an existing template, do some changes in it and then will use it. Technically, we make a copy of the source, make some changes and will use according to the requirements. This is the core concept of the prototype pattern.

For example, assuming that we are creating an Online Leave Application, where someone is asked to fill-in the reason for the leave, start and end date of his/her leave along with details of the approver. A smart thing is for the very first time, we can ask the person to fill in the details and for the subsequent time we can provide an option to copy the first template, do some changes (like changing the start and end date) and allow him to submit.

One important thing that has to be considered in designing prototype pattern is regarding the depth to which we want the object to be copied. In Java terms, whether we want shallow copying or deep copying. In shallow copying, only the primitive properties of the outer object will be copied during the cloning operation, and not the object references. It means that changes made to the target object will be reflected back to the original source object. Whereas, in the case of deep copying, all the primitive and the object references will be copied bit-by-bit, so that it can be ensured that changes done to the target object is not reflected back to the source.

Now, let us see an example for the Prototype pattern what we have discussed till now. Given below is the complete example,

LeaveApplication.java

import java.text.SimpleDateFormat;
import java.util.Date;

public class LeaveApplication implements Cloneable {

	private String reason;
	private Date startDate;
	private Date endDate;
	private Approver approver;

	public LeaveApplication(
			String reason, Date startDate, Date endDate, Approver approver){

		this.reason = reason;
		this.startDate = startDate;
		this.endDate = endDate;
		this.approver = approver;
	}

	public LeaveApplication clone(){

		Approver copyApprover = new Approver(
			approver.getName(), approver.getDesignation());
		LeaveApplication copyApplication = new LeaveApplication(
			reason, ((Date)startDate.clone()), ((Date)endDate.clone()), copyApprover);
		return copyApplication;
	}

	public String toString(){
		return "[Leave Application:" + reason + "," + toString(startDate)
			+ "," + toString(endDate) + approver + "]";
	}

	private String toString(Date date){

		SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yy");
		return format.format(date);
	}

	public String getReason() {
		return reason;
	}

	public void setReason(String reason) {
		this.reason = reason;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public Approver getApprover() {
		return approver;
	}

	public void setApprover(Approver approver) {
		this.approver = approver;
	}
}


This LeaveApplication is the class that we want to clone. It has 3 simple properties namely reason, startDate and endDate and 1 composite property called Approver. Later on we see the class definition for Approver class. Now, let us have a look over the clone() method. Within this method, we create a new instance for the LeaveApplication class and set its properties to the value of the properties of the original object. In this way, we are making a deep cloning of the object and not a shallow cloning. Given below is the class definition for the Approver class,

Approver.java

package tips.pattern.prototype;

public class Approver {

	private String name;
	private String designation;

	public Approver(String name, String designation){
		this.name = name;
		this.designation = designation;
	}

	public String toString(){
		return "[Approver: " + name + "," + designation + "]";
	}

	public String getName() {
		return name;
	}

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

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}
}

Then, we define the main class PrototypeTest for testing the prototype pattern. It creates a new instance of the LeaveApplication class for setting the sickLeave properties. After that, it makes a clone of the sickLeave instance as a casualLeave and modifies some of its properties like the reason and the dates.

PrototypeTest.java

package tips.pattern.prototype;

import java.util.Date;

public class PrototypeTest {

	public static void main(String[] args) {

		Approver manager = new Approver("Johny", "manager");
		LeaveApplication sickLeave =
			new LeaveApplication("Fever", new Date(2007, 3, 20), new Date(2007, 3, 22), manager);
		System.out.println(sickLeave);

		LeaveApplication casualLeave = sickLeave.clone();
		casualLeave.setReason("Vacation");
		casualLeave.setStartDate(new Date(2007, 10, 10));
		casualLeave.setEndDate(new Date(2007, 10, 20));
		System.out.println(casualLeave);
	}
}

分享到:
评论

相关推荐

    Prototype Pattern原型模式

    **原型模式(Prototype Pattern)**是一种基于克隆的创建型设计模式,它的主要目的是为了提高创建新对象的效率,特别是当创建新对象的过程复杂或者资源消耗较大时。在原型模式中,一个已经创建的对象(称为原型)被...

    Advanced Python Programming.epub

    What You Will Learn ...Clone objects using the prototype pattern Use the adapter pattern to make incompatible interfaces compatible Employ the strategy pattern to dynamically choose an algorithm

    c++-设计模式之原型模式(Prototype Pattern)

    原型模式(Prototype Pattern)是一种创建型设计模式,允许通过复制现有对象来创建新对象,而不是通过类构造器。这种模式常用于需要频繁创建相似对象的场景,能够提高性能并减少内存使用。 原型模式的组成 原型接口...

    创建型模式之原型模式(Prototype Pattern)

    **原型模式(Prototype Pattern)详解** 在软件设计中,原型模式是一种创建型设计模式,它提供了一种通过复制已有对象来创建新对象的方式,避免了重复的构造过程,提高了代码的效率和可维护性。原型模式的核心思想...

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

    **原型模式(Prototype Pattern)**是一种创建型设计模式,它允许我们通过复制现有的对象来创建新对象,而不是通过构造函数或工厂方法。这种模式的核心在于,它提供了一种更高效、更灵活的方式来创建新实例,特别是在...

    原型模式 Prototype Pattern

    ### 原型模式 Prototype Pattern #### 概述 原型模式是一种创建型设计模式,它允许用户通过复制现有的实例来创建新的对象,而不是通过传统的构造器来创建对象。这种模式适用于那些创建对象的成本较高,或者当对象...

    Jlink V8固件升级提示Clone的解决方法!

    “the emulator is JLink-Clone, the segger software only support orginal segger device” 然后闪退,IDE崩溃关闭! 解决方案: 1.升级压缩包里的固件(该固件将SN修改为默认的-1)。 2.进入J-Link Commander,...

    Jlink-clone解决办法,替换文件.rar

    当遇到"Jlink-clone"问题时,这通常指的是遇到了非原厂生产的、可能功能受限或者不稳定版本的J-Link设备。这类克隆设备可能会有兼容性问题、性能下降或不支持某些高级功能。本文将深入探讨如何解决Jlink-clone带来的...

    Object-Oriented Analysis and Design 第六章

    Object Oriented Analysis and Design 11Prototype - MotivationThe Prototype pattern provides a way to create new objects by copying existing ones. It's useful when you want to avoid the overhead of ...

    通过java实现原型模式(Prototype Pattern).rar

    Java中有一个内置的Cloneable接口和Object类的clone()方法,它们可以被用来实现对象的克隆。但是,直接使用clone()方法需要处理一些复杂的问题,比如深拷贝和浅拷贝的区别。 压缩包文件代码是一个使用Java实现原型...

    Keil使用非正版Jlink

    Keil环境使用非正版Jlink,使用J-LINK下载或调试的时候会出现严重问题:The connected emulator is a J-link clone. 将文件解压,找到Keil安装目录,替换..\Keil\ARM\Segger

    原型设计模式prototype

    **原型设计模式(Prototype Pattern)**是一种创建型设计模式,它允许我们通过复制现有的对象来创建新对象,而不是通过构造函数来实例化新对象。在面向对象编程中,当我们需要频繁地创建具有相同或相似属性的对象时,...

    Flappy Bird Clone Source Code For Delphi XE5 Firemonkey On Android And IOS

    I accomplished the animation of the firemonkey and the moving ground bar by just using two frames and doing TBitmap.Assign() between them which is not at all the best way to do it but it works for a ...

    QT做的经典2048游戏

    The core is decoupled from the GUI using the observer pattern, so it is easy to pull the code, extract the core and then build a new GUI around it. 1. Download and install Qt ...

    Prototype模式

    **原型模式(Prototype Pattern)**是一种创建型设计模式,它提供了一种通过复制已有对象来创建新对象的方式,而不是通过构造函数。在某些情况下,当创建新对象的成本非常高时(例如,对象需要大量的初始化操作或者从...

    Prototype模式练习

    **原型模式(Prototype Pattern)**是一种常用的软件设计模式,它的主要思想是通过复制已有对象来创建新的对象,从而减少创建新对象的成本。在Java等面向对象编程语言中,原型模式经常被用来实现对象的克隆。在给定的...

    [创建型模式] 原型模式的理解

    原型模式(Prototype Pattern)是一种创建型设计模式,它允许我们通过复制现有的对象来创建新对象,而无需知道具体创建过程的细节。这种模式的核心在于,它提供了一种更灵活的创建对象的方式,避免了复杂的构造过程...

    解决最近升级iar出现的问题,J-Link弹出The connected J-Link is defective

    解决最近升级iar出现的问题,J-Link弹出The connected J-Link is defective,将这几个dll复制粘贴替换掉jLink安装目录(.../Segger/JlinkARMV.../)下的dll,实测可行

    FlexGraphics_V_1.79_D4-XE10.2_Downloadly.ir

    - FIX: The TFlexPanel.FindControlAtPoint method maked virtual to realize RealTime-capability when on mouse cursor moving the flex-object search not occurs. - FIX: After deleting the selected points ...

    .NET设计模式(6):原型模式(PrototypePattern)

    ### .NET设计模式(6):原型模式(Prototype Pattern) #### 概述 在软件工程领域,设计模式提供了一系列经过验证的解决方案,帮助开发者解决常见的软件设计问题。本篇文章聚焦于.NET框架下的“原型模式”...

Global site tag (gtag.js) - Google Analytics