略读设计模式(五)

中介器模式:

abstract class Mediator {
    protected ArrayList<Colleague> colleagues;
    public void register(Colleague colleague) {
        colleagues.add(colleague);
    }
    public abstract void operation();
}
class ConcreteMediator extends Mediator {
    public void operation() {
        ......
        ((Colleague)(colleagues.get(0))).method1();
        ......
    }
}
abstract class Colleague {
    protected Mediator mediator;
    public Colleague(Mediator mediator) {
        this.mediator=mediator;
    }
    public abstract void method1();
    public void method2() {
        mediator.operation();
    }
}

class ConcreteColleague extends Colleague {
    public ConcreteColleague(Mediator mediator) {
        super(mediator);
    }
    public void method1() {
        ......
    }
}

备忘录模式:

public class Originator {
    private String state;
    public Originator(){}
    public Memento createMemento() {
        return new Memento(this);
    }
    public void restoreMemento(Memento m) {
        state = m.state;
    }
    public void setState(String state) {
        this.state = state;
    }
    public String getState() {
        return this.state;
    }
}
class Memento {
    private String state;
    public Memento(Originator o) {
        state = o.getState();
    }
    public void setState(String state) {
        this.state=state;
    }
    public String getState() {
        return this.state;
    }
}
public class Caretaker {
    private Memento memento;
    public Memento getMemento() {
        return memento;
    }
    public void setMemento(Memento memento) {
        this.memento=memento;
    }
}

观察者模式:

abstract class Subject {
    protected ArrayList observers<Observer> = new ArrayList();
    public void attach(Observer observer) {
        observers.add(observer);
    }
    public void detach(Observer observer) {
        observers.remove(observer);
    }
    public abstract void notify();
}

class ConcreteSubject extends Subject {
    public void notify() {
        for(Object obs : observers) {
            ((Observer)obs).update();
        }
    }
}

interface Observer {
    public void update();
}


class ConcreteObserver implements Observer {
    public void update() {
    }
}

书籍地址:http://gof.quanke.name/

发表评论

This site uses Akismet to reduce spam. Learn how your comment data is processed.