JAVA设计模式之行为型模式 Java pattern 设计模式分类

  1. 1. 模板方法模式(Template Method);
  2. 2. 观察者模式(Observer);
  3. 3. 状态模式(State);
  4. 4. 策略模式(Strategy);
  5. 5. 职责链模式(Chain of Responsibility);
  6. 6. 命令模式(Command);
  7. 7. 访问者模式(Visitor);

##行为型模式

对象的创建和结构定义好后,就是他们的行为的设计了。

  • 模板方法模式(Template Method);
  • 观察者模式(Observer);
  • 状态模式(State);
  • 策略模式(Strategy);
  • 职责链模式(Chain of Responsibility);
  • 命令模式(Command);
  • 访问者模式(Visitor);
  • 调停者模式(Mediator);
  • 备忘录模式(Memento);
  • 迭代器模式(Iterator);
  • 解释器模式(Interpreter);

模板方法模式(Template Method);

GoF这样定义:

定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。
Template Method使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

这里我们以画布上画画为例,我们定义一抽象类,其中定义一个渲染方法,渲染时有两个步骤,一个画背景,二能画主体,三加印章。
咱们这里画一个圆和画一个矩形,抽象类中定义渲染时的先后流程,具体的实现有具体的子类进行实现。

代码如下:

package design.pattern.temlatemothod;

/**
* Created by Aaron on 15/9/16.
*/
public abstract class AbstractShape {
public void render(){
this.drawBackground();
this.drawGraphics();
this.drawSignature();
}
abstract void drawSignature();
abstract void drawBackground();
abstract void drawGraphics();

}

package design.pattern.temlatemothod;

/**
* Created by Aaron on 15/9/16.
*/
public class CircleShape extends AbstractShape {
@Override
public void drawSignature() {
System.out.println("draw circle signature!");
}

@Override
public void drawBackground() {
System.out.println("draw circle background! ");
}

@Override
public void drawGraphics() {
System.out.println("draw circle graphics!");
}
}

package design.pattern.temlatemothod;

/**
* Created by Aaron on 15/9/16.
*/
public class RectShape extends AbstractShape {
@Override
public void drawSignature() {
System.out.println("draw rect signature!");
}

@Override
public void drawBackground() {
System.out.println("draw rect background! ");
}

@Override
public void drawGraphics() {
System.out.println("draw rect graphics!");
}
}

package design.pattern.temlatemothod;

/**
* Created by Aaron on 15/9/16.
*/
public class User {
public static void main(String args[]){
new CircleShape().render();
System.out.println("-----");
new RectShape().render();
}
}

输出结果:

draw circle background! 
draw circle graphics!
draw circle signature!
-----
draw circle background! 
draw circle graphics!
draw circle signature!

观察者模式(Observer);

GoF这样定义:

定义对象间的一种一对多的依赖关系 , 以便当一个对象的状态发生改变时 , 所有依赖于它的对象都得到通知并自动刷新。

我们常常会遇到,当一个事件发生时,会有一些监听者进行相应的响应。这里我们的例子是, 当GPS发生变化时,它的订阅者的update的方法就会被调用。

`下面是示例代码:`
package design.pattern.observer;

import java.lang.reflect.Array;
import java.util.ArrayList;

/**
* Created by Aaron on 15/9/16.
*/
public abstract class Subject {
private ArrayList<Observer> observers=new ArrayList<Observer>();
public void addObserver(Observer observer){
this.observers.add(observer);
}
public void removeObserver(Observer observer){
this.observers.remove(observer);
}
public void notifyObserver(){
for(Observer observer:observers){
observer.update(this);
}
}
}

package design.pattern.observer;

import java.awt.*;

/**
* Created by Aaron on 15/9/16.
*/
public class GPSSubject extends Subject {
private Point point;
public void move(Point point){
this.point=point;
this.notifyObserver();
}
}

package design.pattern.observer;

/**
* Created by Aaron on 15/9/16.
*/
public abstract class Observer {
public Observer(){

}
public abstract void update(Subject subject);

}


package design.pattern.observer;

/**
* Created by Aaron on 15/9/16.
*/
public class MapObserver extends Observer {
@Override
public void update(Subject subject) {
System.out.println(this.getClass().getSimpleName()+"_"+this.hashCode()+" observer:"+subject.getClass().getSimpleName()+" position changed;");
}
}

package design.pattern.observer;

import java.awt.*;

/**
* Created by Aaron on 15/9/16.
*/
public class User {
public static void main(String[] args){
GPSSubject subject=new GPSSubject();
subject.addObserver(new MapObserver());
Observer observer1=null;
subject.addObserver(observer1=new MapObserver());
subject.move(new Point(200, 400));
System.out.println("remove one observer from subject's observer list!");
subject.removeObserver(observer1);
subject.move(new Point(200,400));
}
}

状态模式(State);

GoF这样定义: 允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它
所属的类。

以下是示例代码:

package design.pattern.state;

/**
* Created by Aaron on 15/9/20.
*/
public class Context extends AbstractLifeState {
public static OpeningState openingState = new OpeningState();
public static ClosingState closingState = new ClosingState();
public static RunningState runningState = new RunningState();
public static StoppingState stoppingState = new StoppingState();
private AbstractLifeState lifeState;

public Context() {
}

public AbstractLifeState getLifeState() {
return lifeState;
}

public void setLifeState(AbstractLifeState lifeState) {
this.lifeState = lifeState;
this.lifeState.setContext(this);
}

@Override
public void open() {
this.lifeState.open();
}

@Override
public void close() {
this.lifeState.close();
}

@Override
public void run() {
this.lifeState.run();
}

@Override
public void stop() {
this.lifeState.stop();
}
}

package design.pattern.state;

/**
* Created by Aaron on 15/9/20.
*/
public abstract class AbstractLifeState {
protected Context context;

public void setContext(Context context) {
this.context = context;
}

public abstract void open();
public abstract void close();
public abstract void run();
public abstract void stop();
}

package design.pattern.state;

/**
* Created by Aaron on 15/9/20.
*/
public class OpeningState extends AbstractLifeState {
@Override
public void open() {
System.out.println(this.getClass().getSimpleName() + ": operate open");
}

@Override
public void close() {
System.out.println(this.getClass().getSimpleName() + ": operate close");
this.context.setLifeState(Context.closingState);
}

@Override
public void run() {
System.out.println(this.getClass().getSimpleName() + ": operate run");
this.context.setLifeState(Context.runningState);
}

@Override
public void stop() {
System.out.println(this.getClass().getSimpleName()+": operate stop");
this.context.setLifeState(Context.stoppingState);
}
}

package design.pattern.state;

/**
* Created by Aaron on 15/9/20.
*/
public class RunningState extends AbstractLifeState {
@Override
public void open() {
System.out.println(this.getClass().getSimpleName() + ": operate open");
context.setLifeState(Context.openingState);
}

@Override
public void close() {
System.out.println(this.getClass().getSimpleName()+": operate close");
context.setLifeState(Context.closingState);
}

@Override
public void run() {
System.out.println(this.getClass().getSimpleName()+": operate run");
}

@Override
public void stop() {
System.out.println(this.getClass().getSimpleName()+": operate stop");
context.setLifeState(Context.stoppingState);
}
}

package design.pattern.state;

/**
* Created by Aaron on 15/9/20.
*/
public class StoppingState extends AbstractLifeState {
@Override
public void open() {
System.out.println(this.getClass().getSimpleName() + ": operate open");
}

@Override
public void close() {
System.out.println(this.getClass().getSimpleName()+": operate close");
}

@Override
public void run() {
System.out.println(this.getClass().getSimpleName()+": operate run");
}

@Override
public void stop() {
System.out.println(this.getClass().getSimpleName()+": operate stop");
}
}

package design.pattern.state;

/**
* Created by Aaron on 15/9/20.
*/
public class ClosingState extends AbstractLifeState {
@Override
public void open() {
System.out.println(this.getClass().getSimpleName() + ": operate open");
context.setLifeState(Context.openingState);
}

@Override
public void close() {
System.out.println(this.getClass().getSimpleName() + ": operate close");
}

@Override
public void run() {
System.out.println(this.getClass().getSimpleName()+": operate run");
context.setLifeState(Context.runningState);
}

@Override
public void stop() {
System.out.println(this.getClass().getSimpleName()+": operate stop");
context.setLifeState(Context.stoppingState);
}
}

package design.pattern.state;

import design.pattern.flayweight.ConnectionPool;

/**
* Created by Aaron on 15/9/20.
*/
public class User {
public static void main(String[] args){
Context context=new Context();
context.setLifeState(Context.closingState);
context.open();
context.run();
context.close();

}
}

策略模式(Strategy);

GoF这样定义:

定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。

计算器的实现,其中计算的

以下是示例代码:

package design.pattern.strategy;

/**
* Created by Aaron on 15/9/21.
*/
public interface ICalculate {
double calculate(double a,double b);
}

package design.pattern.strategy;

/**
* Created by Aaron on 15/9/21.
*/
public class AddCalculate implements ICalculate {
public double calculate(double a, double b) {
return a+b;
}
}

package design.pattern.strategy;

/**
* Created by Aaron on 15/9/21.
*/
public class DivisionCalculate implements ICalculate {
public double calculate(double a, double b) {
return a/b;
}
}

package design.pattern.strategy;

/**
* Created by Aaron on 15/9/21.
*/
public class SubtractionCalculate implements ICalculate {
public double calculate(double a, double b) {
return a-b;
}
}

package design.pattern.strategy;

/**
* Created by Aaron on 15/9/21.
*/
public class Context {
private ICalculate calculate;
public Context(ICalculate calculate){
this.calculate=calculate;
}

public ICalculate getCalculate() {
return calculate;
}

public void setCalculate(ICalculate calculate) {
this.calculate = calculate;
}

public double calculate(double a,double b){
return this.calculate.calculate(a,b);
}
}

package design.pattern.strategy;

/**
* Created by Aaron on 15/9/21.
*/
public class User {
public static void main(String args[]){
Context context =new Context(new AddCalculate());
double result=context.calculate(20.0,30.3);
System.out.println(result);
context.setCalculate(new DivisionCalculate());
System.out.println(context.calculate(20,40));
}
}

结果输出:

50.3
0.5

职责链模式(Chain of Responsibility);

GoF这样定义:

典型的事例就是我们在Spring中的拦截器和Servlet中的Filter,它们都是现成的责任链模式。

`以下是示例代码:`
package design.pattern.responsibilitychain;

/**
* Created by Aaron on 15/9/29.
*/
public abstract class Handler {
protected Handler successor;

public abstract void process();

public Handler getSuccessor() {
return successor;
}

public void setSuccessor(Handler successor) {
this.successor = successor;
}
}

package design.pattern.responsibilitychain;

/**
* Created by Aaron on 15/9/29.
*/
public class LoggerHandler extends Handler {
@Override
public void process() {
if(getSuccessor()!=null){
System.out.println(getClass().getSimpleName()+",处理请求,并调用下一个处理者");
getSuccessor().process();
}else{
System.out.println(getClass().getSimpleName()+",仅处理,无下一处理者");
}
}
}

package design.pattern.responsibilitychain;

/**
* Created by Aaron on 15/9/29.
*/
public class ValidateHandler extends Handler {
@Override
public void process() {
if(getSuccessor()!=null){
System.out.println(getClass().getSimpleName()+",处理请求,并调用下一个处理者");
getSuccessor().process();
}else{
System.out.println(getClass().getSimpleName()+",仅处理,无下一处理者");
}
}
}

package design.pattern.responsibilitychain;

/**
* Created by Aaron on 15/9/29.
*/
public class User {
public static void main(String[] args) {
Handler validate = new ValidateHandler();
Handler handler = new LoggerHandler();
validate.setSuccessor(handler);
validate.process();
}
}

输出:

ValidateHandler,处理请求,并调用下一个处理者
LoggerHandler,仅处理,无下一处理者

命令模式(Command);

GoF这样定义:

将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数 化;对请求排队或记录请求日志,以及支持可取消的操作。

AudioPlayer系统(转)

  小女孩茱丽(Julia)有一个盒式录音机,此录音机有播音(Play)、倒带(Rewind)和停止(Stop)功能,录音机的键盘便是请求者(Invoker)角色;茱丽(Julia)是客户端角色,而录音机便是接收者角色。Command类扮演抽象命令角色,而PlayCommand、StopCommand和RewindCommand便是具体命令类。茱丽(Julia)不需要知道播音(play)、倒带(rewind)和停止(stop)功能是怎么具体执行的,这些命令执行的细节全都由键盘(Keypad)具体实施。茱丽(Julia)只需要在键盘上按下相应的键便可以了。

  录音机是典型的命令模式。录音机按键把客户端与录音机的操作细节分割开来。

`以下是示例代码:`
package design.pattern.command;

/**
* Created by Aaron on 15/9/29.
*/
public class AudioPlay {
public void play(){
System.out.println("播放....");
}
public void rewind(){
System.out.println("倒带....");
}
public void stop(){
System.out.println("停止....");
}

}

package design.pattern.command;

/**
* Created by Aaron on 15/9/29.
*/
public interface Command {
void execute();
}


package design.pattern.command;

/**
* Created by Aaron on 15/9/29.
*/
public class PlayCommand implements Command {
private AudioPlay audioPlay;

public PlayCommand(AudioPlay audioPlay) {
this.audioPlay = audioPlay;
}

public void execute() {
this.audioPlay.play();
}
}

package design.pattern.command;

/**
* Created by Aaron on 15/9/29.
*/
public class RewindCommand implements Command {
private AudioPlay audioPlay;

public RewindCommand(AudioPlay audioPlay) {
this.audioPlay = audioPlay;
}
public void execute() {
this.audioPlay.rewind();
}
}

package design.pattern.command;

/**
* Created by Aaron on 15/9/29.
*/
public class StopCommand implements Command {
private AudioPlay audioPlay;

public StopCommand(AudioPlay audioPlay) {
this.audioPlay = audioPlay;
}
public void execute() {
this.audioPlay.stop();
}
}

package design.pattern.command;

/**
* Created by Aaron on 15/9/29.
*/
public class Keypad {
private Command playCommand;
private Command rewindCommand;
private Command stopCommand;

public void setPlayCommand(Command playCommand) {
this.playCommand = playCommand;
}

public void setRewindCommand(Command rewindCommand) {
this.rewindCommand = rewindCommand;
}

public void setStopCommand(Command stopCommand) {
this.stopCommand = stopCommand;
}

public void play(){
playCommand.execute();
}
public void rewind(){
rewindCommand.execute();
}
public void stop(){
stopCommand.execute();
}
}

package design.pattern.command;

/**
* Created by Aaron on 15/9/29.
*/
public class User {
public static void main(String[] args) {
AudioPlay audioPlay = new AudioPlay();
PlayCommand playCommand = new PlayCommand(audioPlay);
RewindCommand rewindCommand = new RewindCommand(audioPlay);
StopCommand stopCommand = new StopCommand(audioPlay);

Keypad keypad=new Keypad();
keypad.setPlayCommand(playCommand);
keypad.setRewindCommand(rewindCommand);
keypad.setStopCommand(stopCommand);

keypad.play();
keypad.rewind();
keypad.stop();
keypad.play();
keypad.stop();

}
}

输出结果:

播放....
倒带....
停止....
播放....
停止....

访问者模式(Visitor);

GoF这样定义:

表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元
素的类的前提下定义作用于这些元素的新操作。

`以下是示例代码:`
```
## 调停者模式(Mediator);
GoF这样定义:
>用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互

<div class="col-xs-12">
<img src='' class='col-lg-offset-3 col-lg-6 col-xs-12 thumbnail'/>
</div>
`以下是示例代码:`
```java
## 备忘录模式(Memento); GoF这样定义: > 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到保存的状态。
`以下是示例代码:`
```
## 迭代器模式(Iterator);
GoF这样定义:
>提供一种方法顺序访问一个聚合对象中各个元素,而又不需暴露该对象的内部表示。
<div class="col-xs-12">
<img src='' class='col-lg-offset-3 col-lg-6 col-xs-12 thumbnail'/>
</div>
`以下是示例代码:`
```java
##解释器模式(Interpreter) GoF这样定义: >给定一个语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子。
`以下是示例代码:` ```java ```°