A decorator’s drawing, by definition, will implement the same interface as the component that it decorates. The idea is that client code does not need to be changed. He can rely on the same abstraction as before.
For example:
public interface IMovable { void Move(); } public class Truck : IMovable { public void Move() { Console.Write("moving"); } } public class NoisyMovable : IMovable
If you check out the NoisyMovable class, this is a decorator because it implements the IMovable abstraction and wraps the same thing.
With this you do not need to create many classes such as NoisyVehicle , NoisyTruck , NoisyCar , etc. Just enough Car , Truck ; You can add noise using one decorator.
IMovable movable = new NoisyMovable(new Truck ());//Noisy Truck IMovable movable = new NoisyMovable(new Car());//Noisy car //etc
On the other hand, on the other hand, it is not necessary to wrap the same implementation of the interface that it implements. It can implement one interface and wrap any other.
That you are mistaken, your Truck class accepts an instance of Vehicle . It should not; instead, it should accept any instance of IMovable . It should work with any IMovable implementation.
Sriram sakthivel
source share