Decorator Pattern
Summary: Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Sample Code
Code
public abstract class Camera
{
public string Name { get; set; }
public abstract void TakePhoto();
}
public class DigitalCamera : Camera
{
public override void TakePhoto() => System.Console.WriteLine($"Taking a photo with a {Name}.");
}
public abstract class AdvancedCamera : Camera
{
public Camera Camera { get; protected set; }
public AdvancedCamera(Camera camera)
{
Camera = camera;
}
public abstract void LiveView();
}
public class AdvancedDigitalCamera : AdvancedCamera
{
public AdvancedDigitalCamera(Camera camera) : base (camera) { }
public override void TakePhoto() => Camera.TakePhoto();
public override void LiveView() => System.Console.WriteLine($"Using LiveView in a {Camera.Name}.");
}
Usage
var camera = new AdvancedDigitalCamera(new DigitalCamera { Name = "Canon 70D" });
camera.TakePhoto();
camera.LiveView();
Output
Taking a photo with a Canon 70D.
Using LiveView with a Canon 70D.
Comments
Post a Comment