Design Patterns CC-BY-NC

Maintainer: admin

1Iterator

class MyList implements Iterable<Foo>{
    private ArrayList<Foo> list;
    public Iterator<Foo> iterator(){
        return list.iterator();
    }
}

Class Diagram

2Observer

public class Observable{
    private ArrayList<Observer> obs = new ArrayList<Observer>();
    private boolean changed;
    public attach(Observer o){
        obs.add(o);
    }
    public void setChanged(){
        changed = true;
    }
    public void notifyAll(){
        if(changed){
            for(Observer ob:obs){
                ob.update();
            }
            changed = false;
        }
    }
}

public interface Observer{
    public void update();
}

3Strategy

public interface Comparator<E> {
    public int compare(E a, E b);
}

public Class Sorter<E>{
    public interface Comparator<E> comparator;
    public ArrayList<E> sort(ArrayList<E> e){
        // sort using the comparator
    }
    public void setStrategy(Comparator<E> c){
        this.comparator = c;
    }
}

public class CompareBySize<E> implements Comparator{
    public int compare(E a, E b){
        // implementation
    }
}

public class CompareByColour<E> implements Comparator{
    public int compare(E a, E b){
        // implementation
    }
}

4Composite

public abstract class AbstractFile{
    public String name;
    private int size;
    public abstract int getSize();
}

public class Directory extends AbstractFile{
    private ArrayList<AbstractFile> files;
    public int getSize(){
        int totalSize = 0;
        for(AbstractFile f:files){
            totalSize+=f.getSize();
        }
        return totalSize;
    }
}

public class File extends AbstractFile{
    public int getSize(){
        return size;
    }
}

5Decorator

public interface Frame{
    public void op1();
    public void op2();
    public void op3();
}

public class PlainPart implements Frame{
    public void op1(){
        // implementation
    }

    public void op2(){
        // implementation
    }

    public void op3(){
        // implementation
    }
}

public abstract class DecoratedPart implements Frame{
    private PlainPart p;
    public DecoratedPart(PlainPart p){
        this.p = p;
    }
    public void op1(){
        p.op1();
    }

    public void op2(){
        p.op2();
    }

    public void op3(){
        p.op3();
    }
}

// concrete decorator
public class RedPart extends DecoratedPart{
    public RedPart(Frame p){
        super(p);
    }

    void paint(Graphics g){
    // being red n shit
    }
}

public class Test {
    public main(args){
        DecoratedPart myPart = new RedPart(new(PlainPart());
        // do some magic with myPart!
    }
}

6Facade

// this class is written by some biologist

public class SarcoplasmicReticulum{
    public void releaseCalcium(){
        // implementation
    }
}
public class Myosin{
    public void relax(){
        // implementation
    }
    public void hydrolysis(){
        // implementation
    }
}
public class Troponin{
    public void bindCalcium(){
        // implementation
    }
    public void hydrolysis(){
        // implementation
    }
}
public class Tropomyosin{
    public void fallAway(){
        // implementaion
    }
}
// the facade class
public class MuscleCell{
    private Myosin m;
    private Troponin t;
    private Tropomyosin tm;
    private SarcoplasmicReticulum sr;
    public void contract(){
        sr.releaseCalcium();
        t.bindCalcium();
        t.hydrolysis();
        tm.fallAway();
        m.hydrolysis();
        m.relax();
    }
}

public class SwoleGuy{
    private MuscleCell [] m;
    public void squatz(){
        for(MuscleCell mc : m){
            mc.contract();
        }
    }

    public void oatz(){
        // implementation
    }
}

7Singleton

public class Sun{
    private static Sun ourSun = new Sun();
    public static Sun getInstance(){
        return ourSun;
    }
    private Sun(){}
}

8Flyweight

public class CardFactory {
    private static HashMap<String, Card> cards = new HashMap<>();
    public static Card getCard(String key) {
        if (cards.containsKey(key)) {
            return cards.get(key);
        }else{
            Card c = new Card(key);
            cards.put(key, c);
            return c;
        }
    } 
}
Card c = CardFactory.getCard("Black Ace");
Card d = CardFactory.getCard("Black Ace");
c == d // this is true

9Command

public interface Method{
    public void doSomething();
}

public class Ship{
    private Method thingToDo;
    public setThingToDo(Method m){
        thingToDo = m;
    }
    public doThings(){
        thingToDo.doSomething();
    }
}

public class Commander{
    public void sail(){
        Ship s = new Ship();
        s.setThingToDo(new Method m(){
            public void doSomething(){
                // things
            }
        });
        s.doThings();
    }
}

10Prototype

public interface Prototype{
    public void op1();
    public void op2();
    public void op3();
}

public class PlanA implements Prototype, Cloneable{
    public op1(){
        // implementation
    }
    public op2(){
        // implementation
    }
    public op3(){
        // implementation
    }
    public PlanA clone() throws CloneNotSupportedException{
        return (PlanA)super.clone();
    }
}

public class PlanB implements Prototype, Cloneable{
    public op1(){
        // implementation
    }
    public op2(){
        // implementation
    }
    public op3(){
        // implementation
    }
    public PlanB clone() throws CloneNotSupportedException{
        return (PlanB)super.clone();
    }
}

public class Test{
    public static void main(){
        PlanA a = new PlanA();
        PlanB b = new PlanB();
        Prototype t = (Prototype)a.clone();
        Prototype c = (Prototype)b.clone();
    }
}

11Visitor

public interface Visitable{
    public void accept(Visitor v);
}

public class Book implements Visitable{
    public void accept(Visitor v){
        v.visit(this);
    }
    public void read() {}
    /**
    book stuff
    **/
}
public class Movie implements Visitable{
    public void accept(Visitor v){
        v.visit(this);
    }
    public void watch() {}
    /**
    movie stuff
    **/
}
public interface Visitor{
    public void visit(Book b);
    public void visit(Movie m);
}

public class Person implements Visitor{
    public void visit(Book b){
        b.read();
    }
    public void visit(Movie m){
        m.watch();
    }
}

public class Test{
    public static void main(String [] args){
        ArrayList<Vistable> stuff = new ArrayList<Visitable>();
        /*... put stuff in stuff*/
        Person p = new Person();
        for(Visitable v: stuff){
            v.accept(p); // the person will read/watch depending on the type of stuff
        }
    }
}