BorisKotlyar

Decorator 2

Feb 26th, 2019
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.61 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace Decorator
  5. {
  6.     public interface IWriter
  7.     {
  8.         void Write(string message);
  9.     }
  10.  
  11.     public class ConsoleLogWriter : IWriter
  12.     {
  13.         public void Write(string message)
  14.         {
  15.             Console.WriteLine("ConsoleLogWriter:" + message);
  16.         }
  17.     }
  18.  
  19.     public class FileLogWriter : IWriter
  20.     {
  21.         public void Write(string message)
  22.         {
  23.             Console.WriteLine("FileLogWriter:" + message);
  24.         }
  25.     }
  26.  
  27.     public class ClientWriter : IWriter
  28.     {
  29.         private List<IWriter> _writers = new List<IWriter>();
  30.  
  31.         public void Add(IWriter writer)
  32.         {
  33.             if (!_writers.Contains(writer))
  34.                 _writers.Add(writer);
  35.         }
  36.  
  37.         public void Remove(IWriter writer)
  38.         {
  39.             if (_writers.Contains(writer))
  40.                 _writers.Remove(writer);
  41.         }
  42.  
  43.         public void Write(string message)
  44.         {
  45.             for (var i = 0; i < _writers.Count; i++)
  46.             {
  47.                 _writers[i].Write(message);
  48.             }
  49.         }
  50.     }
  51.  
  52.     class Program
  53.     {
  54.         public static bool UseConsole = true;
  55.         public static bool UseFile = true;
  56.  
  57.         static void Main(string[] args)
  58.         {
  59.             var clientWriter = new ClientWriter();
  60.  
  61.             if (UseConsole)
  62.                 clientWriter.Add(new ConsoleLogWriter());
  63.  
  64.             if (UseFile)
  65.                 clientWriter.Add(new FileLogWriter());
  66.  
  67.             clientWriter.Write("message");
  68.  
  69.             Console.ReadKey();
  70.         }
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment