skm
skm

Reputation: 5649

Hiding a class in C# using interface

I have a class called ResponseBuffer which reads and write into the buffer. I want to hide this class and want to provide only the Read() and Write() APIs to the other classes.

I am planning to use an interface for this purpose. I have written the following sample MWE code.

//*************************************************
//-----Response Buffer (Should be HIDDEN class)
//*************************************************
interface IResponseBuffer
{
    void ReadResponseBuffer();
    void WriteResponseBuffer(string message);
}
class ResponseBuffer : IResponseBuffer //HIDE THIS CLASS
{
    private BlockingCollection<string> ResponseBuffer = new BlockingCollection<string>();

    public void ReadResponseBuffer()
    { }
    public void WriteResponseBuffer(string message)
    { 
        Console.WriteLine(message);
    }
}


//*************************************************
//-----Communication Channel Class - This class needs to use the Response Buffer APIs
//*************************************************
class CommunicationChannel
{
    IResponseBuffer _objResposeBuffer;

    public void SetResponseBufferObject(IResponseBuffer objResponseBuffer)
    {
        this._objResposeBuffer = objResponseBuffer;
    }

    public void StartCommunication()
    {
        _objResposeBuffer .WriteResponseBuffer("Hello");
    }
}

//*************************************************
//-----Main Entry Point for the Program
//*************************************************
class MainWindow_EntryPoint
{        
    ResponseBuffer _objResponseBuffer = new ResponseBuffer();

    CommunicationChannel _objComChannel = new CommunicationChannel();

    //Main enter Constructor
    public MainWindow_EntryPoint()
    {            
        _objComChannel.SetResponseBufferObject(_objResponseBuffer);
        _objComChannel.StartCommunication();
    }
}

Code Explanation: In the code above, I have a ResponseBuffer class, which implements the Read and Write methods to modify the buffer queue. I want to hide this class using an interface called IReposnseBuffer, which provides the APIs called ReadReposneBuffer and WriteReposnseBuffer.

PROBLEM: Though the ComminicationChannel class has no knowledge about the ReponseBuffer class still, I have to create an object of the ReponseBuffer class in the Main.

How can I use the methods of ReposeBuffer class without creating any of its objects directly?

Upvotes: 1

Views: 326

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134811

Create a factory class that returns instances of IResponseBuffer. Your factory class could then return your implementation of that interface (the "hidden" class). Then your calling code only needs to know of the interface and the factory while your factory could return anything that implements that interface.

Upvotes: 3

Related Questions