Hi there,
I am learning more about design patterns and I am trying to implement the Decorator pattern. Essentially I want to extend a computer object to add a string to the end of a description for each new component.
public class Computer {
public Computer(){}
public string Description(){
return "Computer";
}
}
This is the decorator component that each component will inherit from:
public abstract class ComponentDecorator : Computer {
new public abstract string Description();
}
Here are two component classes Monitor and Disk that can decorate the computer class.
public class Monitor : ComponentDecorator {
Computer computer;
public Monitor(Computer c){
this.computer = c;
}
public override string Description(){
return computer.Description () + " and a Monitor";
}
}
public class Disk : ComponentDecorator {
Computer computer;
public Disk(Computer c){
this.computer = c;
}
public override string Description(){
return computer.Description () + " and a Disk";
}
}
Below is the Start method:
void Start(){
Computer computer = new Computer ();
computer = new Disk (computer);
computer = new Monitor (computer);
print("You have a " + computer.Description () + ".");
}
My Expected output is : “You have a Computer and a Monitor and a Disk.”
The Actual output is : “You have a Computer.”
Wouldn’t polymorphism allow the computer to now be treated as the new class Monitor and therefore call the Monitor class description method?