आप जो कह रहे हैं वह आंशिक रूप से सही है कि प्रोटोटाइप पैटर्न का उद्देश्य क्लोनिंग और "नया" से परहेज करके ऑब्जेक्ट बनाने के लिए लागत को कम करना है।
लेकिन इसका मतलब यह नहीं है कि आप ऑब्जेक्ट क्लोन करने के लिए पैटर्न का उपयोग कर सकते हैं। अन्य महत्वपूर्ण विचार हैं
नीचे एक उदाहरण विभिन्न प्रकार पेज बैनर की कि अलग-अलग हो थोड़ा
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");
}
}
ओह और अपने मामले में बनाने के लिए एक प्रोटोटाइप PageBanner उदाहरण का उपयोग करता है है, अपने प्रोटोटाइप वस्तु की क्लास Cloneable
मार्कर इंटरफ़ेस को लागू किया है
मैंने विकिपीडिया की इस पैटर्न की परिभाषा भी जांच की। मैं मानता हूं कि यह कोई समझ नहीं आता है (वर्गों को किसी भी तरह से तत्काल नहीं किया जा रहा है) जब तक कि आप ऑब्जेक्ट कैश का लाभ उठा रहे हों। –