一、责任链模式(Chain of Responsiblity Pattern)
二、命令模式(Command Pattern)
三、解释器模式(Interpreter Pattern)
四、迭代器模式(Interator Pattern)
五、中介者模式(Mediator Pattern)
六、备忘录模式(Memento Pattern)
七、观察者模式(Observer Pattern)
当对象一对多关系时,其中某个对象被修改时,则自动通知它依赖对象。
定义对象一对多关系依赖关系,一个对象状态发生改变,所有依赖于他的对象得到通知并被自动更新。
1.Subject类创建
public class Subject{
private List<Observer> observers=new ArryList<Observer>();
private int state;
public int getState(){
return state;
}
public void setState(int state){
this.state=state;
notifyAllObserver();
}
public void attach(Observer observer){
observers.add(observer);
}
public void notityAllObserver(){
for(Observer observer:observers){
observer.update();
}
}
}
2.创建Observer类
public abstract class Observer{
protected Subject subject;
public void update();
}
3.创建实体观察者类
public class BinaryObserver extends Observer{
public BinaryObserver(Subject subject){
this.subject=subject;
this.subject.attatch(this);
}
@override
public void update(){
System.out.println("Binary String"+Integer.toBinaryString(subject.getState()));
}
}
public class OctalObserver extends Observer{
public OctalObserver(Subject subject){
this.subject=subject;
this.subject.attach(this);
}
@override
public void update(){
System.out.println("Octal:"+Integer.toOctalString(subject.getState));
}
}
public class HexaObserver{
public HexaObserver(Subject subject){
this.subject=subject;
this.subject.attach(this);
}
@override
public void update(){
System.out.println("Hexa:"+Integer.toHexaString(subject.getState()));
}
}
```
4.ObserverPatternDemo.java
```java
public class ObserverPatternDemo{
public void static main(String[] args){
Subject subjec=new Subject();
new BinaryObserver(subject);
new OctalObserver(subject);
new HexaObserver(subject);
subject.setState(11);
}
}
```
## 九、状态模式(State Pattern)
## 十、空对象模式(Null Object Pattern)
## 十一、策略模式(Strategy Pattern)
## 十二、模板模式(Template Pattern)
## 十三、访问者模式(Visitor Pattern)