Design patterns that have been said many times---prototype mode

Source: Internet
Author: User
Tags abstract getdate

[Turn your rational mind slowly into a conditioned reflex]

In this paper, we introduce the prototype model, the topic structure of the article is consistent with the upper. Practice, let's take a look at the environment of our example project:

Operating system: Win7 x64

Other software: Eclipse MARS,JDK7

--------------------------------------------------------------------------------------------------------------- ----------------------

Classic problem: object replication, cloning.

Thinking Analysis:

Point one: Support shallow cloning.

Point two: Support deep cloning.

Example Project:

Error Wording:

Create a Templet.java file with the following details:

Package com.csdn.ingo.gof_prototype;

public class Window {public
	static void Main (string[] args) {
		Templet a = new Templet ("Templeta");
		A.setcontext ("AAAAA");
		A.settime ("010101");
		A.setcompany ("CompanyA");
		
		Templet B = A;
		B.setname ("Templetb");
		Templet C = A;
		C.setname ("templetc");
		
		A.display ();
		B.display ();
		C.display ();
		System.out.println (A.hashcode ());
		System.out.println (B.hashcode ());
		System.out.println (C.hashcode ());
	}
}

cause of error:

First, let's look at the output of the main method above:

Name:templetc,context:aaaaa,time:010101,company:companya
Name:templetc,context:aaaaa,time:010101,company: CompanyA
Name:templetc,context:aaaaa,time:010101,company:companya
17198255
17198255
17198255
ABC three objects have identical addresses in memory, representing the same object. (This part of the concept is very basic, please crossing remember).

recommended Notation (1): Shallow clone (value type)


Create a Prototype.java file with the following details:

Package com.csdn.ingo.gof_prototype.one;

Public abstract class Prototype {
	
	private String ID;
	
	Public Prototype (String ID) {
		this.id=id;
	}
	Public String getId () {
		return ID;
	}
	public void SetId (String id) {
		this.id = ID;
	}
	
	Public abstract Prototype Clone ();
}
Create a Concreteprototypea file with the following details:

Package com.csdn.ingo.gof_prototype.one;

public class Concreteprototypea extends Prototype implements cloneable {public

	Concreteprototypea (String id) {
  super (ID);
	}

	@Override public
	Prototype Clone () {
		return (Prototype) This.clone ();
	}

	@Override Public
	Object Clone () {
		Concreteprototypea CPA = NULL;
		try {
			CPA = (CONCRETEPROTOTYPEA) super.clone ();
		} catch (Clonenotsupportedexception e) {
			E.printstacktrace ();
		}
		return CPA;
	}
}
Create a Window.java file with the following details:

Package com.csdn.ingo.gof_prototype.one;

public class Window {public
	static void Main (string[] args) {
		Concreteprototypea a = new Concreteprototypea ("Ingo ");
		Concreteprototypea B = (Concreteprototypea) a.clone ();
		System.out.println (A.hashcode ());
		System.out.println (B.hashcode ());
	}
}
Observation output:

1149197
20761102
recommended Notation (2): Shallow clone (reference type)


Create a Collection.java file with the following details:

Package com.csdn.ingo.gof_prototype.two;

Import Com.csdn.ingo.gof_prototype.one.ConcretePrototypeA;

public class Collection implements cloneable {
	private String prop1;
	Private String prop2;
	
	Public String GetProp1 () {
		return prop1;
	}
	public void SetProp1 (String prop1) {
		this.prop1 = Prop1;
	}
	Public String GetProp2 () {
		return prop2;
	}
	public void SetProp2 (String prop2) {
		this.prop2 = prop2;
	}
	@Override Public
	Object Clone () {
		Collection co = null;
		try {
			co = (Collection) super.clone ();
		} catch (Clonenotsupportedexception e) {
			e.printstacktrace ();
		}
		return co;
	}
}
Create a Concreteprototypea.java file with the following details:
Package com.csdn.ingo.gof_prototype.two;

public class Concreteprototypea extends Prototype implements cloneable {
	private Collection Collection =new collectio n ();
	
	Public Collection GetCollection () {
		return Collection;
	}

	public void Setcollection (Collection Collection) {
		this.collection = Collection;
	}

	Public Concreteprototypea (String ID) {
		super (ID);
	}

	@Override public
	Prototype Clone () {
		return (Prototype) This.clone ();
	}

	@Override Public
	Object Clone () {
		Concreteprototypea CA = null;
		try {
			CA = (Concreteprototypea) super.clone ();
		} catch (Clonenotsupportedexception e) {
			E.printstacktrace ();
		}
		return CA;
	}
}
Create a Prototype.java file with the following details:

Package com.csdn.ingo.gof_prototype.two;

Public abstract class Prototype {
	
	private String ID;
	
	Public Prototype (String ID) {
		this.id=id;
	}
	Public String getId () {
		return ID;
	}
	public void SetId (String id) {
		this.id = ID;
	}
	
	Public abstract Prototype Clone ();
}
Create a Window.java file with the following details:

Package com.csdn.ingo.gof_prototype.two;

public class Window {public
	static void Main (string[] args) {
		Concreteprototypea a = new Concreteprototypea ("in Go ");
		Concreteprototypea B = (Concreteprototypea) a.clone ();
		Collection CA = a.getcollection ();
		CA.SETPROP1 ("A1");
		CA.SETPROP2 ("A2");
		Collection cb = B.getcollection ();
		CB.SETPROP1 ("B1");
		CB.SETPROP2 ("B2");
		System.out.println (A.hashcode ());
		System.out.println (B.hashcode ());
		System.out.println (A.getcollection (). Hashcode ());
		System.out.println (B.getcollection (). Hashcode ());
	}
}
Observation output:

1396421
15105042
31164770
31164770
recommended Notation (3): Deep Clone (dedicated)


Create a Colleation.java file with the following details:

Package com.csdn.ingo.gof_prototype.three;

Import Com.csdn.ingo.gof_prototype.two.ConcretePrototypeA;

public class Collection implements cloneable{
	
	private String date;
	Private String Company;
	Public String getDate () {
		return date;
	}
	public void SetDate (String date) {
		this.date = date;
	}
	Public String Getcompany () {
		return company;
	}
	public void Setcompany (String company) {
		this.company = Company;
	}
	@Override Public
	Object Clone () {
		Collection CA = null;
		try {
			CA = (Collection) super.clone ();
		} catch (Clonenotsupportedexception e) {
			e.printstacktrace ();
		}
		return CA;
	}
	@Override public
	String toString () {
		return ' Collection [date= "+ Date +", company= "+ company +"] ";
	}
}
Create a Prototype.java file with the following details:
Package com.csdn.ingo.gof_prototype.three;

public class Prototype implements cloneable {
	private String name;
	private Collection work;
	Public Prototype (String name) {
		this.name = name;
		Work = new Collection ();
	}
	Private Prototype (Collection work) {
		this.work = (Collection) work.clone ();
	}
	Public String GetName () {
		return name;
	}
	public void SetName (String name) {
		this.name = name;
	}
	Public Collection getwork () {
		return work;
	}
	public void Setwork (Collection work) {
		this.work = work;
	}
	public void Setwke (String date,string company) {
		work.setdate (date);
		Work.setcompany (company);
	}
	@Override public
	String toString () {
		return "Prototype [name=" + name + ", work=" + work.tostring () + "]";
	}
	@Override public
	Object Clone () {
		Prototype CA = new Prototype (this.work);
		Ca.setname (name);
		return CA;
	}
}
Create a Window.java file with the following details:
Package com.csdn.ingo.gof_prototype.three;

public class Window {public

	static void Main (string[] args) {
		Prototype a = new Prototype ("Ingo");
		System.out.println (A.hashcode ());
		A.setwke ("n", "AAA");
		Prototype B = (Prototype) a.clone ();
		System.out.println (B.hashcode ());
		B.setwke ("The", "BBB");
		Prototype C = (Prototype) a.clone ();
		System.out.println (C.hashcode ());
		C.setwke ("The", "CCC");
		System.out.println (A.tostring ());
		System.out.println (B.tostring ());
		System.out.println (C.tostring ());
	}
}
recommended Notation (4): Deep Clone (Universal)


Create a Collection.java file with the following details:

Package com.csdn.ingo.gof_prototype.four;

Import java.io.Serializable;

public class Collection implements Serializable {
	private static final long serialversionuid = 1L;
	private String date;
	Private String Company;

	Public String getDate () {
		return date;
	}

	public void SetDate (String date) {
		this.date = date;
	}

	Public String Getcompany () {
		return company;
	}

	public void Setcompany (String company) {
		this.company = Company;
	}

	@Override Public
	Object Clone () {
		Collection CA = null;
		try {
			CA = (Collection) super.clone ();
		} catch (Clonenotsupportedexception e) {
			e.printstacktrace ();
		}
		return CA;
	}

	@Override public
	String toString () {
		return ' Collection [date= "+ Date +", company= "+ company +"] ";
	}
}

Create a Prototype.java file with the following details;

Package com.csdn.ingo.gof_prototype.four;
Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;

Import java.io.Serializable;
	public class Prototype implements Serializable {private static final long serialversionuid = 1L;
	private String name;

	Private Collection work;
		Public Prototype (String name) {this.name = name;
	Work = new Collection ();
	} public String GetName () {return name;
	} public void SetName (String name) {this.name = name;
	} public Collection Getwork () {return work;
	} public void Setwork (Collection work) {this.work = work;
		public void Setwke (string date, string company) {work.setdate (date);
	Work.setcompany (company);
	} @Override Public String toString () {return "Prototype [name=" + name + ", work=" + work.tostring () + "]"; } public Prototype Clone () {Bytearrayoutputstream bao = new BytearrayoutputstreaM ();
		ObjectOutputStream Oos;
			try {oos = new ObjectOutputStream (BAO);

			Oos.writeobject (this);
			Bytearrayinputstream bis = new Bytearrayinputstream (Bao.tobytearray ());
			ObjectInputStream Ois;
			OIS = new ObjectInputStream (bis);
		Return (Prototype) ois.readobject ();
		} catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
		} catch (ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();
	} return null;
 }
}
Create a Window.java file with the following details:

Package com.csdn.ingo.gof_prototype.four;

public class Window {public

	static void Main (string[] args) {
		Prototype a = new Prototype ("Ingo");
		System.out.println (A.hashcode ());
		A.setwke ("n", "AAA");
		Prototype B = (Prototype) a.clone ();
		System.out.println (B.hashcode ());
		B.setwke ("The", "BBB");
		Prototype C = (Prototype) a.clone ();
		System.out.println (C.hashcode ());
		C.setwke ("The", "CCC");
		System.out.println (A.tostring ());
		System.out.println (B.tostring ());
		System.out.println (C.tostring ());
	}
} <span style= "Font-family:microsoft yahei;font-size:14px;" >
</span>
question: The difference between a shallow clone and a deep clone. Shallow clone: All variables of the copied object contain the same value as the original object, and all references to other objects still point to the original object. In other words: The simple type in the object member variable is copied, and the Reference object type, only the reference is copied, still points to the original object, and the object still has only one copy.

Deep cloning: All variables of the copied object contain the same value as the original object, and all references to other objects also copy a referenced object. In other words: The simple type in the object member variable is copied, and the reference object type is copied, not just the reference, but the reference object.

Pattern Summary: standard UML structure diagram:


Concept Summary:

Prototype mode: Specifies the kind of object created with the prototype instance, and creates a new object by opening the prototypes.

Components: Prototype (Prototype Class), Concreteprototype (specific subclass) two parts.

Note: This article only takes Java as an example to illustrate, other languages of the prototype model, please crossing self-learning. Reflection: Application Scenarios:

Create a similar object. On top of that, creating new objects takes a lot of resources, taking a long time to create a scene. When a backup is created within the system, the object changes less and takes a long time to save. The object contains a combination of properties, and the number of objects is small, considering the efficiency of execution.

Advantages:

When objects are more complex, prototype mode simplifies the creation process and increases the efficiency of creation. Scalability is good. The client interacts directly with the abstract class, improving the flexibility and extensibility of both parties. Provides deep cloning, shallow cloning two ways for its use.

Disadvantages:

You must create a clone method for each object, and any changes to the cloned object will directly violate the open and closed principle. The process of deep cloning requires multiple complex processes such as IO. Need to deal with abnormal situations in a timely manner. Deeply nested clones are difficult to manage and implement.

--------------------------------------------------------------------------------------------------------------- ----------------------

So far, the design patterns that have been said many times---the end of prototype mode


Resources:

Book: "Big Talk design mode"

Other Posts: http://blog.csdn.NET/lovelion/article/details/7563445


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.