Bilel Msekni
Bilel Msekni
Tech Lead & Frontend Expert
"A general, reusable solution to a commonly occurring problem"
- Wikipedia
(Creational)
Create a class responsible for instanciating and returning the instance on subsequent calls.
How can we guarantee that one and only one
instance of a class can be created?
(Creational)
public sealed class Singleton {
private static readonly Singleton instance = new Singleton();
private Singleton() {}
public static Singleton Instance => instance
}
...
private static readonly object padlock = new object();
public static Singleton Instance {
get {
if (instance == null) {
lock(padlock) {
if (instance == null) instance = new Singleton();
}
}
return instance;
}
}
(Creational)
(Structural)
How can we access a large number of classes with a complex internal interaction in a simple but safe way?
Introduce a dedicated interface class that simplifies the view of the class collection
(Structural)
Suppliers
Payment
Delivery
...
Facade
(Structural)
public class Facade {
private Suppliers _suppliers;
private Payment _payment;
public Facade(Suppliers suppliers, Payment payment) {
this._suppliers = suppliers;
this._payment = payment;
}
public void Purchase(string id, int quantity) {
Command command = _suppliers.provision(id, quantity);
Payment payment = _payment.pay(command.Amount);
}
}
class Client {
public void Buy(Facade facade) {
string id = GetElementId();
int quantity = GetQuantity();
facade.Purchase(id, quantity);
}
}
class Client {
private Suppliers _suppliers;
private Payment _payment;
public Client(Suppliers suppliers, Payment payment) {
this._suppliers = suppliers;
this._payment = payment;
}
public void Buy(Facade facade) {
string id = GetElementId();
int quantity = GetQuantity();
Command command = _suppliers.provision(id, quantity);
Payment payment = _payment.pay(command.Amount);
}
}
(Structural)
(Behavior)
How can we deal with two or more classes which sometimes interact, but can also be used separately?
Keep objects from referring to one another explicitly by puting each interaction between objects in a separate (Mediator) class.
(Behavior)
(Behavior)
(Behavior)
Over time a mediator can evolve into a God Object.