Strategy Pattern

Strategy pattern, comes under behaviour patterns. Why it is using much and how effecting strategy of development. Main strategy is defining common operations and seperate them different classes. Thus we can maintain easly.

In our example, we will create a repository class which connecting different db types but doing same things.

As we see, it is seperated different classes, so we can add different type of db such as mysql or mongo without changing our architecture.

namespace strategy_pattern {
    public interface IdbOperations<T> {
        void insert(T data);
        void update(T data);
        void delete(T data);
        List<T> getlist();
    }
}
namespace strategy_pattern {
    public class MssqlDbOperations : IdbOperations<object>
    {
        public void delete(object data)
        {
            throw new System.NotImplementedException();
        }
        public List<object> getlist()
        {
            throw new System.NotImplementedException();
        }
        public void insert(object data)
        {
            throw new System.NotImplementedException();
        }
        public void update(object data)
        {
            throw new System.NotImplementedException();
        }
    }
}
namespace strategy_pattern {
    public class MysqlDbOperations : IdbOperations<object>
    {
        public void delete(object data)
        {
            throw new System.NotImplementedException();
        }
        public List<object> getlist()
        {
            throw new System.NotImplementedException();
        }
        public void insert(object data)
        {
            throw new System.NotImplementedException();
        }
        public void update(object data)
        {
            throw new System.NotImplementedException();
        }
    }
}
namespace strategy_pattern
{
    class Program
    {
        static void Main(string[] args)
        {
            MssqlDbOperations operationsMssql = new MssqlDbOperations();
            operationsMssql.insert(new Object());
            MysqlDbOperations operationsMysql = new MysqlDbOperations();
            operationsMysql.insert(new Object());
        }
    }
}

Consequently, we can add new classes for new types of db thus we don’t need to change existing code. Also we stayed loyal to S of SOLID principles.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *