Question

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?

Was it helpful?

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.

OTHER TIPS

You could have another layer of abstraction for the database operations. This layer should be responsible for taking all the database requests centralizing the access. Connections strings should be configured externally, and the data mapping layer could access them directly.

The Repository Pattern is a good pattern for this layer that you can apply. It can sit between your domain objects and the data mapping layers.

Since you don't like Lennaert answer of passing the connection to your class why not reverse it and create a connection class that uses a simple command pattern and pass your class to it as a the parameter?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top