A frequently-used design pattern is the Decorator. This is also known as a mixin (or they might not be the very same thing but certainly they are related).
Typically you might need to create a class that implements a certain interface and uses another class that implements that exact interface but you need to provide some additional feature(s). An example would be a class that adds transactional behavior to an existing data-access class (a naive example) :
public interface IDataAccess
{
void AddCustomerInvoice(Invoice invoice, User user);
}
public class DataAccess : IDataAccess
{
public void AddCustomerInvoice(Invoice invoice, User user)
{
InsertInvoice(invoice, user);
UpdateCustomerDebt(user, invoice.Total);
}
// ... the rest of the implementation
}
public class TransactionalDataAccess : IDataAccess
{
private readonly IDataAccess _dataAccess;
public TransactionalDataAccess(IDataAccess dataAccess)
{
if (dataAccess == null)
{
throw new ArgumentNullException();
}
_dataAccess = dataAccess;
}
public void AddCustomerInvoice(Invoice invoice, User user)
{
using(var tx = new TransactionScope())
{
_dataAccess.AddCustomerInvoice(invoice, user);
tx.Complete();
}
}
// ... the rest of the implementation
}
Another type of example would be the Adapter design pattern. An example would be providing access to a (static) class (that may be out of your control) in a mock-able manner. That is, implement another class, non-static, which implements a defined interface and eases unit-testing :

Recent Comments