设计模式笔记——Prototype

本文介绍如何在Java中使用Cloneable接口实现原型模式,并通过实例演示了克隆对象的操作,包括对象属性复制及自定义克隆逻辑。

Java 里面实现Prototype

使用Cloneable接口


package prototype.pattern;

import java.util.Date;

/**
 * 
 * @author Real H LI
 *
 */
public class Prototype implements Cloneable {

	private Date date;
	private String dateStr;
	private String ID;
	
	public Prototype(){
		this.date=new Date();
		this.dateStr=date.toString();
		setID("YYYYYYY");
	}
	
	@Override
	protected Object clone() throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		try {
			return this.getClass().newInstance();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public String getDateStr() {
		return dateStr;
	}

	public void setID(String iD) {
		ID = iD;
	}

	public String getID() {
		return ID;
	}
	
	

}

package prototype.pattern;
/**
 * 
 * @author Real H LI
 *
 */
public class PrototypePattern {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Prototype prototype = new Prototype();
		System.out.println(prototype.getDateStr());

		System.out.println("-------------------------------");
		Prototype temp;
		try {
			for (int i = 0; i < 10; i++) {
				temp = (Prototype) prototype.clone();
				System.out.println(temp.getDateStr());
				temp.setID(String.valueOf(i));
			}
		} catch (CloneNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("-------------------------------");
		System.out.println(prototype.getID());
		
	}

}


转载于:https://www.cnblogs.com/leestar/archive/2012/08/14/2810628.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值