मैंने सजावटी डिजाइन पैटर्न का एक उदाहरण पढ़ा। मुझे समझ में आया कि यह डिज़ाइन पैटर्न गतिशील रूप से एक विशेष उदाहरण के व्यवहार को संशोधित करता है। उदाहरण जो मैंने नीचे दिया है वह भी समझ में आता है। जिस बिंदु को मैं समझ नहीं पाया वह यह है कि जब मैं दूध वस्तु पर c.getCost()
पर कॉल करता हूं, तो यह 1.5 लौटाता है। केवल Simplecoffee
का getCost()
1 लौटाता है, लेकिन दूध वापसी पर c.getCost
कहां से आता है?सजावटी पैटर्न श्रृंखला विधि कैसे कॉल करता है?
क्या कोई भी Milk
कक्षा और Simplecoffee
कक्षा के बीच के लिंक को समझ सकता है, और विधि के निष्पादन को getCost()
दूध वस्तु के साथ बुलाए जाने पर कैसे बहती है? getCost()
विधि वापसी 1.5 कैसे करता है?
//Decorator Design Pattern
interface Coffee {
public double getCost();
public String getIngredients();
}
class Simplecoffee implements Coffee {
public double getCost() {
return 1;
}
public String getIngredients() {
return "Coffee";
}
}
abstract class CoffeeDecorator implements Coffee {
protected Coffee decoratedcoffee;
protected String ingredientseparator = ":";
public CoffeeDecorator(Coffee decoratedcoffee) {
this.decoratedcoffee = decoratedcoffee;
}
public double getCost() {
return decoratedcoffee.getCost();
}
public String getIngredients() {
return decoratedcoffee.getIngredients();
}
}
class Milk extends CoffeeDecorator {
public Milk(Coffee decoratedcoffee) {
super(decoratedcoffee);
System.out.println("Milk Constructor");
}
public double getCost() {
return super.getCost() + 0.5;
}
public String getIngredients() {
return super.getIngredients() + ingredientseparator + "milk";
}
}
public class Decorator {
public static void main(String[] ar) {
System.out.println("calling simplecoffee in main");
Coffee c = new Simplecoffee();
System.out.println("Cost:" + c.getCost());
c = new Milk(c);
System.out.println("Cost:" + c.getCost());
}
}
आप एक 'Thread.dumpStack()' 'की getCost' विधि में' Simplecoffee' पता लगाने के लिए डाल सकता है। –
असल में, जब आपने सी = नया दूध कहा (सी) आप कॉफीडिकोरेटर कन्स्ट्रक्टर को विरासत के माध्यम से बुला रहे हैं, जो सिंपलकोफी इंस्टेंस को इसके क्षेत्र (इंटरफ़ेस कॉफी के माध्यम से संदर्भित) के रूप में सेट करता है, और सजाए गए coffee.getCost() को कॉल करता है; विरासत के माध्यम से अपनी मूल विधि में जाता है जो 1 देता है और 0.5 – drgPP
जोड़ता है "दूध वस्तु के साथ बुलाए जाने पर विधि कैसे बहती है" एलओएल – Reg