行为型模式主要关注对象间的通信,它们提供了一种方法来定义对象之间的相互作用,以及怎样分配责任。以下是一些行为型模式的简要说明和Java代码示例:
模板方法模式(Template Method Pattern)
模板方法模式定义了一个算法的骨架,将一些步骤的执行延迟到子类中。
// 抽象类,即模板
abstract class AbstractClass {
public final void templateMethod() {
baseOperation1();
baseOperation2();
concreteOperation();
// 钩子方法,可以被子类重写
hookMethod();
}
protected abstract void concreteOperation();
protected void baseOperation1() {
System.out.println("基本操作1");
}
protected void baseOperation2() {
System.out.println("基本操作2");
}
// 钩子方法
protected void hookMethod() {
System.out.println("钩子方法");
}
}
// 具体实现
class ConcreteClass extends AbstractClass {
@Override
protected void concreteOperation() {
System.out.println(“具体实现”);
}
}
// 客户端代码
class Client {
public static void main(String[] args) {
AbstractClass abstractClass = new ConcreteClass();
abstractClass.templateMethod();
}
}
策略模式(Strategy Pattern)
策略模式定义了一系列算法,并将每一个算法封装起来,使它们可以互换。
// 策略接口
interface Strategy {
void algorithm();
}
// 具体策略
class ConcreteStrategyA implements Strategy {
@Override
public void algorithm() {
System.out.println(“算法A”);
}
}
class ConcreteStrategyB implements Strategy {
@Override
public void algorithm() {
System.out.println(“算法B”);
}
}
// 上下文
class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.algorithm();
}
}
// 客户端代码
class Client {
public static void main(String[] args) {
Context context = new Context(new ConcreteStrategyA());
context.executeStrategy();
context.setStrategy(new ConcreteStrategyB());
context.executeStrategy();
}
}
观察者模式(Observer Pattern)
观察者模式定义了对象之间的一对多依赖关系,当一个对象状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。
// 主题接口
interface Subject {
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
}
// 观察者接口
interface Observer {
void update();
}
// 具体主题
class ConcreteSubject implements Subject {
private List observers = new ArrayList<>();
private int state;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
notifyObservers();
}
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
observers.remove(o);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update();
}
}
}
// 具体观察者
class ConcreteObserver implements Observer {
@Override
public void update() {
System.out.println(“观察者被通知”);
}
}
// 客户端代码
class Client {
public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject();
ConcreteObserver observer = new ConcreteObserver();
subject.registerObserver(observer);
subject.setState(1); // 通知观察者
}
}
迭代器模式(Iterator Pattern)
迭代器模式提供一种顺序访问聚合对象中的元素的方法,不暴露其内部的表示。
// 聚合接口
interface Aggregate {
Iterator createIterator();
}
// 具体聚合
class ConcreteAggregate implements Aggregate {
private List items = new ArrayList();
public void add(Object item) {
items.add(item);
}
@Override
public Iterator createIterator() {
return new ConcreteIterator(this);
}
}
// 迭代器接口
interface Iterator {
boolean hasNext();
Object next();
}
// 具体迭代器
class ConcreteIterator implements Iterator {
private ConcreteAggregate aggregate;
private int currentIndex = 0;
public ConcreteIterator(ConcreteAggregate aggregate) {
this.aggregate = aggregate;
}
@Override
public boolean hasNext() {
return currentIndex < aggregate.items.size();
}
@Override
public Object next() {
Object item = aggregate.items.get(currentIndex);
currentIndex++;
return item;
}
}
// 客户端代码
class Client {
public static void main(String[] args) {
ConcreteAggregate aggregate = new ConcreteAggregate();
aggregate.add(“Item1”);
aggregate.add(“Item2”);
Iterator iterator = aggregate.createIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
责任链模式(Chain of Responsibility Pattern)
责任链模式使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。
// 请求接口
interface Request {
int getRequestNumber();
}
// 处理者抽象类
abstract class Handler {
protected Handler successor;
public Handler(Handler successor) {
this.successor = successor;
}
public void setSuccessor(Handler successor) {
this.successor = successor;
}
public abstract void handleRequest(Request request);
}
// 具体处理者
class ConcreteHandlerA extends Handler {
public ConcreteHandlerA(Handler successor) {
super(successor);
}
@Override
public void handleRequest(Request request) {
if (request.getRequestNumber() == 1) {
System.out.println("处理请求1");
} else if (this.successor != null) {
successor.handleRequest(request);
}
}
}
// 客户端代码
class Client {
public static void main(String[] args) {
Handler handlerA = new ConcreteHandlerA(null);
Handler handlerB = new ConcreteHandlerB(handlerA);
Handler handlerC = new ConcreteHandlerC(handlerB);
handlerC.handleRequest(new Request1(1));
}
}
命令模式(Command Pattern)
命令模式将请求或操作封装为一个对象,从而使你可以用不同的请求对客户进行参数化。
// 命令接口
interface Command {
void execute();
}
// 具体命令
class ConcreteCommand implements Command {
private Receiver receiver;
public ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
receiver.action();
}
}
// 接收者
class Receiver {
public void action() {
System.out.println(“执行操作”);
}
}
// 调用者
class Invoker {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void executeCommand() {
command.execute();
}
}
// 客户端代码
class Client {
public static void main(String[] args) {
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
Invoker invoker = new Invoker();
invoker.setCommand(command);
invoker.executeCommand();
}
}
中介者模式(Mediator Pattern)
中介者模式定义一个中介对象来封装一系列对象之间的交互。
// 同事接口
interface Colleague {
void setMediator(Mediator mediator);
void send(String message);
}
// 具体同事
class ConcreteColleagueA implements Colleague {
private Mediator mediator;
public void setMediator(Mediator mediator) {
this.mediator = mediator;
}
@Override
public void send(String message) {
mediator.notifyColleague(this, message);
}
}
class ConcreteColleagueB implements Colleague {
private Mediator mediator;
public void setMediator(Mediator mediator) {
this.mediator = mediator;
}
@Override
public void send(String message) {
mediator.notifyColleague(this, message);
}
}
// 中介者
class Mediator {
private List colleagues = new ArrayList<>();
public void addColleague(Colleague colleague) {
colleagues.add(colleague);
}
public void notifyColleague(Colleague colleague, String message) {
for (Colleague c : colleagues) {
if (c != colleague) {
c.receive(message);
}
}
}
}
// 具体同事接收消息
class Colleague {
public void receive(String message) {
System.out.println(“收到消息:” + message);
}
}
// 客户端代码
class Client {
public static void main(String[] args) {
Mediator mediator = new Mediator();
ConcreteColleagueA colleagueA = new ConcreteColleagueA();
ConcreteColleagueB colleagueB = new ConcreteColleagueB();
colleagueA.setMediator(mediator);
colleagueB.setMediator(mediator);
mediator.addColleague(colleagueA);
mediator.addColleague(colleagueB);
colleagueA.send(“消息A”);
colleagueB.send(“消息B”);
}