Last active
February 5, 2018 23:28
-
-
Save SelaO/bf640649608e6cd46cf3d2851453cb14 to your computer and use it in GitHub Desktop.
C# Decorator pattern implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// C# decorator example where every concrete decorator needs to implement doConcrete() instead of remembering to call base.doit() | |
// based on this example: https://sourcemaking.com/design_patterns/decorator/java/1 | |
using System; | |
namespace Project1 | |
{ | |
class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
ICommonInterface[] vars = { new X(new Core()), new Y(new X(new Core())), new Z(new Y(new X(new Core()))) }; | |
foreach (var item in vars) | |
{ | |
item.doit(); | |
Console.Write(" "); | |
} | |
// ADX ADXDY ADXDYDZ | |
} | |
} | |
public interface ICommonInterface | |
{ | |
void doit(); | |
} | |
public abstract class Decorator : ICommonInterface | |
{ | |
private readonly ICommonInterface core; | |
public Decorator(ICommonInterface core) | |
{ | |
this.core = core; | |
} | |
public void doit() | |
{ | |
core.doit(); | |
Console.Write("D"); | |
doConcrete(); | |
} | |
protected abstract void doConcrete(); | |
} | |
public class Core : ICommonInterface | |
{ | |
public void doit() | |
{ | |
Console.Write("A"); | |
} | |
} | |
public class X : Decorator | |
{ | |
public X(ICommonInterface core) : base(core) | |
{ | |
} | |
protected override void doConcrete() | |
{ | |
Console.Write("X"); | |
} | |
} | |
public class Y : Decorator | |
{ | |
public Y(ICommonInterface core) : base(core) | |
{ | |
} | |
protected override void doConcrete() | |
{ | |
Console.Write("Y"); | |
} | |
} | |
public class Z : Decorator | |
{ | |
public Z(ICommonInterface core) : base(core) | |
{ | |
} | |
protected override void doConcrete() | |
{ | |
Console.Write("Z"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment