Articles → CSHARP → Tight And Loose Coupling C#
Tight And Loose Coupling C#
Tight Coupling
using System;
public class SQLDataAccess {
public void ExecuteQuery(string query) {
Console.WriteLine(query);
}
}
public class ConsumerClass {
SQLDataAccess _dal;
public ConsumerClass(SQLDataAccess dal) {
this._dal = dal;
}
public void Execute() {
_dal.ExecuteQuery("Executing SQLDataAccess query");
}
}
class Program {
static void Main(string[] args) {
ConsumerClass cc = new ConsumerClass(new SQLDataAccess());
cc.Execute();
Console.ReadKey();
}
}
Loose Coupling
using System;
public interface IDatabase {
void ExecuteQuery(string query);
}
public class SQLDataAccess: IDatabase {
public void ExecuteQuery(string query) {
Console.WriteLine("SQLServer query");
}
}
public class MySQLDataAccess: IDatabase {
public void ExecuteQuery(string query) {
Console.WriteLine("MySQL query");
}
}
public class ConsumerClass {
IDatabase _dal;
public ConsumerClass(IDatabase dal) {
this._dal = dal;
}
public void Execute() {
_dal.ExecuteQuery("Executing query");
}
}
class Program {
static void Main(string[] args) {
ConsumerClass cc = new ConsumerClass(new SQLDataAccess());
cc.Execute();
cc = new ConsumerClass(new MySQLDataAccess());
cc.Execute();
Console.ReadKey();
}
}
Click to Enlarge