您所说的部分正确,因为原型模式的目标是通过克隆和避免“新”来降低创建对象的成本。
但这并不意味着您可以使用该模式来克隆对象。还有其他重要的考虑
- 使用原型对象作为所有其他实例的“制造者”。
- 从给定的实例中创建“几乎”相似的实例,原型
总而言之,原型的目标是:
- 通过克隆“原型对象”来降低创建对象的成本
- 当通过原型创建的对象将与原型对象略有不同。
下面是一个使用原型 PageBanner 实例创建不同类型的页面横幅的示例,这些横幅略有不同
import java.awt.Dimension;
import java.io.Serializable;
/**
* This class also acts as a factory for creating prototypical objects.
*/
public class PageBanner implements Serializable, Cloneable {
private String slogan;
private String image;
private String font;
private Dimension dimension;
// have prototype banner from which to derive all other banners
private static final PageBanner PROTOTYPE = new PageBanner("",
"blank.png", "Verdana", new Dimension(600, 45));
PageBanner(String slogan, String image, String font,
Dimension dim) {
this.slogan = slogan;
this.image = image;
//... other assignments
}
// getters and setters..
public String toString() {
return new StringBuilder("PageBanner[")
.append("Slogan=").append(slogan)
.append("Image=").append(image)
.append("Font=").append(font)
.append("Dimensions=").append(dimension)
.toString();
}
protected Object clone() {
Object cln = null;
try {
cln = super.clone();
}catch(CloneNotSupportedException e) {
// ignore, will never happen
}
return cln;
}
/**
* This is the creational method that uses the prototype banner
* to create banners and changes it slightly (setting slogan and image)
*/
public static PageBanner createSloganBanner(String slogan, String image) {
PageBanner banner = (PageBanner) PROTOTYPE.clone();
banner.slogan = slogan;
banner.image = image;
return banner;
}
/**
* Another creational method that uses the prototype banner
* to create banners and changes it slightly (setting image)
*/
public static PageBanner createImageBanner(String image) {
PageBanner banner = (PageBanner) PROTOTYPE.clone();
banner.image = image;
return banner;
}
// similarly you can have a number of creational methods with
// different parameters for different types of banners that
// vary slightly in their properties.
// main... (for illustration)
public static void main(String[] args) {
// both these banners are created from same prototypical instance
PageBanner slogan = PageBanner.createSloganBanner(
"Stackoverflow Rocks", "stack.png");
PageBanner img = PageBanner.createImageBanner("stackBanner.png");
}
}
哦,在你的情况下,让你的原型对象的类实现Cloneable
标记接口