设计模式——原型模式

原型模式是指原型实例指定创建对象的种类,并且通过复制这些原型对象创建新的对象
原型模式主要适用于以下场景
1.类初始化消耗资源比较多
2.使用new生成一个对象是一个比较繁琐的过程(数据准备,访问权限)
3.构造函数比较复杂
4.在循环体中产生大量对象

1.浅克隆

首先创建原型Prototype接口

public interface Prototype {
	
	Prototype clone();

}

创建具体需要克隆的类

public class ConcretePrototype implements Prototype {
	
	private String name;
	
	private int age;
	
	private List hobbies;

	

	public String getName() {
		return name;
	}



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



	public int getAge() {
		return age;
	}



	public void setAge(int age) {
		this.age = age;
	}



	public List getHobbies() {
		return hobbies;
	}



	public void setHobbies(List hobbies) {
		this.hobbies = hobbies;
	}



	@Override
	public Prototype clone() {
		ConcretePrototype con = new ConcretePrototype();
		con.setAge(this.age);
		con.setName(this.name);
		con.setHobbies(this.hobbies);
		return con;
	}

}

创建Client类
public class Client {
	
	private Prototype prototype;

	public Client(Prototype prototype) {
		this.prototype = prototype;
	}
	
	public Prototype startClone(Prototype con) {
		return con.clone();
	}
	

}

浅克隆只是完整复制了值类型数据,没有赋值引用对象。换而言之所有引用对象仍然指向原来的对象

2.深克隆

public Object deepClone() {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(this);
			
			ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
			ObjectInputStream ois = new ObjectInputStream(bis);
			
			QiTianDaSheng copy = (QiTianDaSheng) ois.readObject();
			copy.birthday = new Date();
			return copy;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

3.克隆破坏单例模式

如果我们克隆的目标对象是单例对象,那么意味着深克隆会破坏单例模式。实际上为了防止克隆破坏单例的思路很简单,禁止深克隆即可,要么我们的单例类不实现Cloneable接口,要么我们重写clone()方法,在clone()方法中返回单例对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值