GOF23 设计模式 之原型模式

原型模式就是克隆模式,克隆一份在这个基础上去修改;

克隆完成后如果副本上面所有的的属性和本体没有任何耦合,也就是说没有使用任何一个的同一个应用引用,那么称为深克隆

如果还有耦合 称为浅拷贝;

************************

克隆模式一般分为两种:

1,通过 java的clone()方法来实现,这样实现起来可能是浅克隆,需要一点手段来实现深克隆;

2,通过序列化反序列化字节码实现 深克隆,这边代码就不实现了,大约理解是啥意思就行了,技术手段而已。

************************

代码实现

1, 浅克隆

package prototype;

import java.util.Date;

public class Sheep implements Cloneable {
	private String name;
	private Date brithday;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public Date getBrithday() {
		return brithday;
	}
	public void setBrithday(Date brithday) {
		this.brithday = brithday;
	}
	
	public Sheep(String name, Date brithday) {
		super();
		this.name = name;
		this.brithday = brithday;
	}
	protected Object clone() throws CloneNotSupportedException {
		// 对象伤的浅克隆方法
		Object obj = super.clone();
		return obj;
		 
	} 
	public void name() {
		
	}
	
	
}


// client 调用
package prototype;

import java.awt.desktop.ScreenSleepEvent;
import java.util.Date;

public class Client {

	public static void main(String[] args) throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		
		Date date = new Date(1222142313L);
		
		
		Sheep sheep1= new Sheep("111",date);
		System.out.println(sheep1.getName());
		System.out.println(sheep1.getBrithday());
		
		Sheep sheep2 = (Sheep) sheep1.clone();
		System.out.println(sheep2.getName());
		System.out.println(sheep2.getBrithday());

	}

}

2,深克隆


package prototype;

import java.util.Date;

public class Sheep implements Cloneable {
	private String name;
	private Date brithday;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public Date getBrithday() {
		return brithday;
	}
	public void setBrithday(Date brithday) {
		this.brithday = brithday;
	}
	
	public Sheep(String name, Date brithday) {
		super();
		this.name = name;
		this.brithday = brithday;
	}
	protected Sheep clone() throws CloneNotSupportedException {
		// 对象伤的浅克隆方法
		Sheep obj = (Sheep) super.clone();
		obj.brithday = (Date)this.brithday.clone();
		return obj;
		 
	} 
	public void name() {
		
	}
	
	
}

// client 调用
package prototype;

import java.awt.desktop.ScreenSleepEvent;
import java.util.Date;

public class Client {

	public static void main(String[] args) throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		
		Date date = new Date(11L);
		
		
		Sheep sheep1= new Sheep("111",date);
		 
		
		Sheep sheep2 = (Sheep) sheep1.clone();
		
		date.setTime(1111111111L);
		
		System.out.println(sheep1.getName());
		System.out.println(sheep1.getBrithday());
		
		System.out.println(sheep2.getName());
		System.out.println(sheep2.getBrithday());

	}

}
发布了189 篇原创文章 · 获赞 10 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/wangrong111222/article/details/104103069