Search code examples
c#strategy-pattern

C# Strategy pattern and database access


I am new to design patterns and now I want to implement the Strategy patern. Here's my code:

namespace StrategyPattern
{
    public interface ISendBehavior
    {
        void Send();
    }

    public class SendAppointment : ISendBehavior
    {
        public void Send()
        {
            // send item
        }
    }

    public class SendTask : ISendBehavior
    {
        public void Send()
        {
            // send item
        }
    }

    public class SendItem
    {
        ISendBehavior _sendBehavior;

        public SendItem(ISendBehavior sendbehavior)
        {
            _sendBehavior = sendbehavior;
        }

        public void Send()
        {
            _sendBehavior.Send();
        }
    }

    /* CALL */

    public class Aanroep
    {
        public void Verzenden()
        {
            SendItem app = new SendItem(new SendAppointment());
            app.Send();
        }

    }
}

In the method Send in the class SendAppointment the item will be send. My question is, do I have to connect to the database in this class? If so, then I also have to connect to the database in SendTask. But at this point I am repeating myself right? So if a connection string changes, i have to modify this in every class. How can I solve this problem?


Solution

  • How about initializing each implementor of ISendBehavior with yet another object that's responsible for the database connection?

    Your Verzenden()-implementation would be something like

    IDatabaseConnection connection = new DatabaseConnection();
    
    SendItem app = new SendItem( new SendAppointment( connection ) );
    

    and your ISendBehavior.Send() would be implemented like this

    _databaseConnection.Send( ... ); // fill behavior-specific information here (perhaps with properties)
    

    This way, you can reuse that IDatabaseConnection for any other classes.