設計模式-原型模式

設計模式-原型模式

定義

用原型實例指定建立對象的種類,而且經過拷貝這些原型建立出一個新的對象。
 簡單理解就是用一個已有的對象克隆出一個新的對象
UML

優勢

  • 性能優良,原型模式使用的是內存的二進制流的拷貝,比直接new對象性能好不少,特別是循環產生大量對象時,能夠更好的提現其優勢
  • 逃避構造函數的約束。這既是優勢,也是缺點,內存拷貝不會通過構造函數,很容易被忽略形成錯誤

缺點

實現

public class Student {

	private String name;

	private String targetClass;

	private int age;

	private String address;


	public String getName() {
		return name;
	}

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

	public String getTargetClass() {
		return targetClass;
	}

	public void setTargetClass(String targetClass) {
		this.targetClass = targetClass;
	}

	public int getAge() {
		return age;
	}

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

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}
}
public class Notice implements Cloneable{

	private String receiver;

	private String subject;

	private String msg;

	private String address;

	public Notice(Student student) {
		this.receiver = student.getName();
		this.address = student.getAddress();
	}

	public String getReceiver() {
		return receiver;
	}

	public void setReceiver(String receiver) {
		this.receiver = receiver;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public Notice  clone(){
		Notice notice = null;

		try {
			notice = (Notice) super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return notice;
	}
}
import java.util.Random;

public class Client {

	private static int MAX_COUNT = 10;

	public static void main(String[] args) {

		int i = 0;
		Notice noticePrototype = new Notice(new Student());
		noticePrototype.setSubject("入學通知書");
		noticePrototype.setMsg("咱們將於九月一日開學");

		while (i < MAX_COUNT){
			Notice notice = noticePrototype.clone();
			notice.setAddress(getRandString(20));
			notice.setReceiver(getRandString(5) +" 同窗");
			sendNotice(notice);
			i++;
		}
	}

	private  static  void sendNotice(Notice notice){
		System.out.println("發送通知書給 " + notice.getReceiver());
		System.out.println("  address = [" + notice.getAddress() + "]");
	}


	public static String getRandString(int length){
		String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random=new Random();
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<length;i++){
			int number=random.nextInt(62);
			sb.append(str.charAt(number));
		}

		return sb.toString();
	}
}

使用場景

  • 資源優化場景 ,類初始化時須要消耗大量資源,並且須要反覆新生成這個類
  • 性能和安全要求場景,經過new產生一個對象須要很是繁瑣的數據準備或訪問權限
  • 一個對象供多個修改者使用,能夠拷貝多個對象供調用者使用
  • 易於工廠方法模式結合使用

擴展

  • 須要注意深拷貝和淺拷貝
  • 拷貝時容易忽略構造函數的執行引發沒必要要的錯誤
相關文章
相關標籤/搜索