Complete_CSharp_Design_Patterns
Complete_CSharp_Design_Patterns
1. Singleton Pattern
---------------------
Intent:
Ensure a class has only one instance and provide a global point of access to it.
Use Case:
Code Example:
private Singleton() { }
get {
lock (_lock) {
if (_instance == null)
return _instance;
}
Pros:
Cons:
- Hidden dependencies
------------------------------------------------------------
--------------------------
Intent:
Define an interface for creating an object but let subclasses decide which class to instantiate.
Use Case:
Code Example:
Pros:
Cons:
------------------------------------------------------------
-----------------------------
Intent:
Provide an interface for creating families of related objects without specifying their concrete classes.
Use Case:
Code Example:
interface IButton {
void Paint();
interface IGUIFactory {
IButton CreateButton();
Pros:
Cons:
------------------------------------------------------------
4. Adapter Pattern
-------------------
Intent:
Convert the interface of a class into another interface the client expects.
Use Case:
Code Example:
interface ITarget {
void Request();
class Adaptee {
Pros:
- Improve compatibility
Cons:
------------------------------------------------------------
5. Observer Pattern
--------------------
Intent:
One-to-many dependency between objects so when one object changes, others are notified.
Use Case:
interface IObserver {
interface ISubject {
void Notify();
observer.Update(message);
message = msg;
Notify();
Pros:
- Loose coupling
Cons:
- Hard to debug
------------------------------------------------------------
6. Strategy Pattern
--------------------
Intent:
Define a family of algorithms, encapsulate each one, and make them interchangeable.
Use Case:
Code Example:
interface IStrategy {
void Execute();
}
class Context {
Pros:
- Eliminates conditionals
Cons:
------------------------------------------------------------
-------------------------------
|------------------|-------------|---------------------------------------|-------------------------|