0

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.

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44

1 Answers1

0

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();
     }
 }
KyloRen
  • 2,691
  • 5
  • 29
  • 59
Mojtaba Tajik
  • 1,725
  • 16
  • 34
  • 1
    No need to say thanks for answers. if the answer is useful and solve the problem just mark it as answer. Good Luck. – Mojtaba Tajik Sep 09 '18 at 07:48
  • press the green tick , if this is the right solution, so everyone could benefit as well @TetsuaKeito – Wesam Sep 09 '18 at 09:12