Decorator Design Pattern - Not extending object behavior
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?
Answer by MaxGuernseyIII · Apr 11, 2018 at 06:07 PM
One of the key characteristics of the Decorator pattern is that the client shouldn't have to know when a particular added behavior is in place. Most importantly, each decorator object, itself, should not know whether it is decorating the "base" behavior or another decorator.
You achieve this by making the base behavior have an abstraction that all the decorators implement and on which they all depend.
What you have stumbled upon is an often-difficult-to-illustrate distinction between a Proxy pattern (sometimes one thing can stand in for another thing) and a Decorator pattern (sometimes you want to add one or more behaviors to a thing). A lot of proxy objects decorate and it's pretty much impossible to decorate without also proxying so people are confused by that but one of the most important distinctions (there are others but this one matters here) is that proxies are allowed to know the exact type they proxy and decorators ought not be.
Long story short, get rid of that ComponentDecorator class, make Computer's Description() method virtual, and have your decorators inherit from Computer.
Your answer
Follow this Question
Related Questions
Flip 3D Character Rotation 180 on Y axis 1 Answer
How to fix snake behavior in Unity3d? 0 Answers
How can I make this character move smoothly? 1 Answer
Navigation in VR Mode?!! 0 Answers
Unity3d Character Spawn Point 0 Answers