Search code examples
c#eventsdining-philosopher

How can i write an adaptive method to use my library in the right way?


I have a library and theres one problem with the logic in my program. If you can help me - i will say you : "Thank you" . really big thanks. Code :

 public class Report
{

    /// <summary>
    /// An empty constructor, just instantiates the object.
    /// </summary>
    public Report()
    {

    }

    /// <summary>
    /// A method that receives a message from another object,
    /// and prints it out to the Console.
    /// </summary>
    /// <param name="message">The message to be printed.</param>
    public void ReceiveMessage(String message)
    {
        Console.WriteLine(message);
    }
}

private Report reportObject;

public void EnterThinkingState() {

        Thread.Sleep(rng.Next(1000) + 1);
        Status = "thinking";
        reportObject.ReceiveMessage(Name + " is " + Status);
        Thread.Sleep(rng.Next(1000) + 1);
    }

the Question is : My classes - are a library. How can i create an adaptive method (Receive) that a user could use to output information wherever he wants(logger,console,file e.t.c). should i use virtual methods? Or create an interface? Or how can i bind it with events?I know how to use events if we talk about typical situation. Thank you for the help. And, again, sorry for my bad English.


Solution

  • You can use different approach to achieve this. The below code show how to define an interface and use it :

     public interface IReceiverBase
     {
         void ReceiveMessage(string message);
     }
    
     public class Report
     {
         private readonly IReceiverBase _iReceiverBase;
    
         public Report(IReceiverBase iReceiverBase)
         {
             _iReceiverBase = iReceiverBase;
         }
    
         public void DoSomething()
         {
             // Do something here
             _iReceiverBase.ReceiveMessage("Something done ...");
         }
     }
    
     public class ConsoleMessageReceiver : IReceiverBase
     {
         public void ReceiveMessage(string message)
         {
             Console.WriteLine(message);
         }
     }
    
     public class DebugMessageReceiver : IReceiverBase
     {
         public void ReceiveMessage(string message)
         {
             Debug.WriteLine(message);
         }
     }
    
     class Program
     {
         static void Main(string[] args)
         {
             var repConsole = new Report(new ConsoleMessageReceiver());
             repConsole.DoSomething();
    
             var repDebug = new Report(new DebugMessageReceiver());
             repDebug.DoSomething();
    
             Console.Read();
         }
     }