# Design Patterns
# Resources
# Creational
# Simple Factory
It is used to create instances of a class. Rather than calling the constructor. It hides implementation details of the constructor.
# Factory
Create instances of different subclasses, based on which one is necessary. It's based on different concrete creators.
# Abstract factory
Factory of factory. Abstract factory is to define an interface of factory first and create different implementations of factories.
# Builder
foo = FooBuilder().setPropertyA().setPropertyB().build()
# Structural
# Adaptor
Adaptor is like a wrapper such that you can make one class satisfy an interface by calling methods of another class.
# Bridge
Bridge is to decouple two features. e.g. a webpage can have different subpages and different themes. Each of them should be independent feature instead of bundled together. Then we bridge a page with a theme to have them working together.
# Composition
Composition creates different types of instances with the same form (i.e. with the same properties), such that the caller can treat them in the same way. This is similar to having the same interface.
# Decorator
Decorators wraps around an object and changes its state.
coffee = SimpleCoffee()
addMilk(addSugar(addCream(coffee)))
coffee.describe()
# Facade
Facade simplifies the interface by hiding complexities in a system.
// Example
class Computer {
public turnOn() {
this.plugIn();
this.tapStartButton();
this.turnOnDisk();
...
}
}
# Flyweight
Share as much data as possible between objects to minimize memory consumption.
# Proxy
Proxy pattern makes one class functions the same as another class. It's like a wrapper but adds more functionalities to the original class (e.g. adding security check).
# Behavioral
# Chain of responsibility
bank = Bank(10)
paypal = Paypal(20)
bitcoin = Bitcoin(30)
bank.setSuccessor(paypal)
paypal.setSuccessor(bitcoin)
bank.pay(40)
When one account cannot pay all the balance, it defers to the successor to pay the remaining balance.
# Command
Command can be used to implement a transaction based system where all commands are stored. Command interface usually implements three methods, execute, undo and redo.
# Iterator
# Mediator
Think about a computer, which has CPU, Network drive, etc. They should not communicate directly with each other. They should go through the motherboard and the motherboard is mediator.
class Motherboard implements Mediator {
private cpu;
private cdcard;
public void changed(Device device) {
if (device == this.cpu) {
this.cpu.handleChange()
}
if (device == this.cdcard) {
this.cdcard.handleChange()
}
// ...
}
}
# Memento
# Observer
# Visitor
For different types of object, you have to treat them differently. Link
class Visitor {
public visitA(ElementA el) {}
public visitB(ElementB el) {}
}
for (obj of objects) {
if (obj instanceof ElementA) {
visitor.visitA(obj);
}
if (obj instanceof ElementB) {
visitor.visitB(obj);
}
}