赞
踩
策略模式是一种行为设计模式,它定义了一系列算法,将每个算法封装在独立的策略类中,并使它们可以互相替换。策略模式可以让算法独立于客户端而变化,使得算法可以在不影响客户端的情况下动态地切换或替换。
结构
场景
优点
缺点
示例
// 定义支付策略接口 interface PaymentStrategy { void pay(double amount); } // 实现不同支付策略的具体类 class CreditCardPayment implements PaymentStrategy { @Override public void pay(double amount) { System.out.println("使用信用卡支付: " + amount + "元"); } } class PayPalPayment implements PaymentStrategy { @Override public void pay(double amount) { System.out.println("使用PayPal支付: " + amount + "元"); } } class WechatPayment implements PaymentStrategy { @Override public void pay(double amount) { System.out.println("使用微信支付: " + amount + "元"); } } // 购物车类 class ShoppingCart { private PaymentStrategy paymentStrategy; public void setPaymentStrategy(PaymentStrategy paymentStrategy) { this.paymentStrategy = paymentStrategy; } // 模拟计算购物车总价 public double calculateTotal() { // 假设这里是实际的计算购物车总价的过程 return 100.0; } // 支付方法,根据支付策略进行支付 public void pay() { double totalAmount = calculateTotal(); paymentStrategy.pay(totalAmount); } } // 测试类 public class StrategyPatternExample { public static void main(String[] args) { // 创建购物车对象 ShoppingCart cart = new ShoppingCart(); // 选择支付方式 PaymentStrategy creditCardPayment = new CreditCardPayment(); PaymentStrategy paypalPayment = new PayPalPayment(); PaymentStrategy wechatPayment = new WechatPayment(); // 设置支付方式 cart.setPaymentStrategy(creditCardPayment); // 进行支付 cart.pay(); // 设置另一种支付方式 cart.setPaymentStrategy(paypalPayment); // 进行支付 cart.pay(); // 设置第三种支付方式 cart.setPaymentStrategy(wechatPayment); // 进行支付 cart.pay(); } }
使用信用卡支付: 100.0元
使用PayPal支付: 100.0元
使用微信支付: 100.0元
迭代器模式是一种行为设计模式,用于提供一种方法来顺序访问聚合对象中的元素,而不需要暴露其内部表示。通过使用迭代器模式,可以在不暴露聚合对象的内部结构的情况下,遍历聚合对象中的元素。
结构
场景
优点
缺点
示例
import java.util.ArrayList; import java.util.Iterator; import java.util.List; // 迭代器接口 interface Iterator<T> { boolean hasNext(); T next(); } // 具体迭代器类 class ConcreteIterator<T> implements Iterator<T> { private List<T> list; private int position; public ConcreteIterator(List<T> list) { this.list = list; this.position = 0; } @Override public boolean hasNext() { return position < list.size(); } @Override public T next() { if (hasNext()) { T item = list.get(position); position++; return item; } return null; } } // 聚合接口 interface Aggregate<T> { Iterator<T> createIterator(); } // 具体聚合类 class ConcreteAggregate<T> implements Aggregate<T> { private List<T> list; public ConcreteAggregate() { this.list = new ArrayList<>(); } public void addItem(T item) { list.add(item); } @Override public Iterator<T> createIterator() { return new ConcreteIterator<>(list); } } // 客户端代码 public class Client { public static void main(String[] args) { // 创建具体聚合类 ConcreteAggregate<String> aggregate = new ConcreteAggregate<>(); // 向聚合类中添加元素 aggregate.addItem("Item 1"); aggregate.addItem("Item 2"); aggregate.addItem("Item 3"); // 创建迭代器并遍历元素 Iterator<String> iterator = aggregate.createIterator(); while (iterator.hasNext()) { String item = iterator.next(); System.out.println(item); } } }
Item 1
Item 2
Item 3
访问者模式是一种行为设计模式,用于在不改变元素类的前提下定义作用于元素对象的新操作。它将操作封装在独立的访问者类中,使得可以在不修改元素类的情况下,根据不同的访问者对象,实现对元素对象的不同操作。
结构
场景
优点
缺点
示例
import java.util.ArrayList; import java.util.List; // 元素接口 interface Element { void accept(Visitor visitor); } // 具体元素类 class ConcreteElementA implements Element { @Override public void accept(Visitor visitor) { visitor.visit(this); } public void operationA() { System.out.println("ConcreteElementA is performing operation A."); } } // 具体元素类 class ConcreteElementB implements Element { @Override public void accept(Visitor visitor) { visitor.visit(this); } public void operationB() { System.out.println("ConcreteElementB is performing operation B."); } } // 访问者接口 interface Visitor { void visit(ConcreteElementA element); void visit(ConcreteElementB element); } // 具体访问者类 class ConcreteVisitor implements Visitor { @Override public void visit(ConcreteElementA element) { System.out.println("ConcreteVisitor is visiting ConcreteElementA."); element.operationA(); } @Override public void visit(ConcreteElementB element) { System.out.println("ConcreteVisitor is visiting ConcreteElementB."); element.operationB(); } } // 结构对象类 class ObjectStructure { private List<Element> elements = new ArrayList<>(); public void addElement(Element element) { elements.add(element); } public void removeElement(Element element) { elements.remove(element); } public void accept(Visitor visitor) { for (Element element : elements) { element.accept(visitor); } } } // 客户端类 public class Main { public static void main(String[] args) { // 创建元素对象 Element elementA = new ConcreteElementA(); Element elementB = new ConcreteElementB(); // 创建访问者对象 Visitor visitor = new ConcreteVisitor(); // 创建结构对象 ObjectStructure objectStructure = new ObjectStructure(); objectStructure.addElement(elementA); objectStructure.addElement(elementB); // 访问元素 objectStructure.accept(visitor); } }
ConcreteVisitor is visiting ConcreteElementA.
ConcreteElementA is performing operation A.
ConcreteVisitor is visiting ConcreteElementB.
ConcreteElementB is performing operation B.
观察者模式是一种行为设计模式,它定义了一种一对多的依赖关系,当一个对象的状态发生变化时,其所有依赖者(观察者)都会收到通知并自动更新。在观察者模式中,主题(也称为可观察者或被观察者)维护着一组观察者,并在状态发生变化时通知它们。
结构
优点
缺点
场景
示例
import java.util.ArrayList; import java.util.List; // 主题接口(Subject Interface) interface Subject { void attach(Observer observer); void detach(Observer observer); void notifyObservers(); int getState(); } // 具体主题类(Concrete Subject Class) class ConcreteSubject implements Subject { private List<Observer> observers = new ArrayList<>(); private int state; public int getState() { return state; } public void setState(int state) { this.state = state; notifyObservers(); } public void attach(Observer observer) { observers.add(observer); } public void detach(Observer observer) { observers.remove(observer); } public void notifyObservers() { for (Observer observer : observers) { observer.update(); } } } // 观察者接口(Observer Interface) interface Observer { void update(); } // 具体观察者类(Concrete Observer Class) class ConcreteObserver implements Observer { private Subject subject; public ConcreteObserver(Subject subject) { this.subject = subject; } public void update() { System.out.println("Observer received update. New state: " + subject.getState()); } } // 客户端代码 public class Main { public static void main(String[] args) { // 创建具体主题对象 ConcreteSubject subject = new ConcreteSubject(); // 创建具体观察者对象,并将主题对象注册为观察者 ConcreteObserver observer = new ConcreteObserver(subject); subject.attach(observer); // 改变主题对象的状态 subject.setState(10); // 取消观察者的注册 subject.detach(observer); // 再次改变主题对象的状态 subject.setState(20); } }
Observer received update. New state: 10
命令模式是一种行为设计模式,它将请求封装成一个对象,从而允许用不同的请求对客户进行参数化,并且可以支持请求的排队、日志记录、撤销和重做等操作。
结构
场景
优点
缺点
示例
import java.util.*; // 命令接口 interface Command { void execute(); } // 具体命令:开灯 class TurnOnLightCommand implements Command { private Light light; public TurnOnLightCommand(Light light) { this.light = light; } @Override public void execute() { light.turnOn(); } } // 具体命令:关灯 class TurnOffLightCommand implements Command { private Light light; public TurnOffLightCommand(Light light) { this.light = light; } @Override public void execute() { light.turnOff(); } } // 接收者:灯 class Light { public void turnOn() { System.out.println("灯已打开"); } public void turnOff() { System.out.println("灯已关闭"); } } // 调用者:遥控器 class RemoteControl { private Map<String, Command> commands = new HashMap<>(); public void setCommand(String commandName, Command command) { commands.put(commandName, command); } public void pressButton(String commandName) { Command command = commands.get(commandName); if (command != null) { command.execute(); } else { System.out.println("未找到命令:" + commandName); } } } // 客户端代码 public class Main { public static void main(String[] args) { // 创建灯对象 Light light = new Light(); // 创建命令对象 Command turnOnCommand = new TurnOnLightCommand(light); Command turnOffCommand = new TurnOffLightCommand(light); // 创建遥控器对象 RemoteControl remoteControl = new RemoteControl(); // 设置遥控器按钮对应的命令 remoteControl.setCommand("开灯", turnOnCommand); remoteControl.setCommand("关灯", turnOffCommand); // 模拟按下遥控器按钮 remoteControl.pressButton("开灯"); // 输出:灯已打开 remoteControl.pressButton("关灯"); // 输出:灯已关闭 } }
灯已打开
灯已关闭
模板方法模式是一种行为设计模式,用于定义一个算法的框架,将一些步骤延迟到子类中实现。模板方法模式定义了一个抽象类,其中包含了算法的骨架和一些基本方法,而具体的实现则由子类来完成。
结构
场景
优点
缺点
示例
// 咖啡制作的抽象类 abstract class CoffeeTemplate { // 冲泡咖啡的模板方法 public final void makeCoffee() { boilWater(); // 烧水 brewCoffee(); // 冲泡咖啡 pourInCup(); // 倒入杯中 addCondiments(); // 加入调料 } // 抽象方法:冲泡咖啡 abstract void brewCoffee(); // 抽象方法:加入调料 abstract void addCondiments(); // 具体方法:烧水 void boilWater() { System.out.println("烧开水"); } // 具体方法:倒入杯中 void pourInCup() { System.out.println("将咖啡倒入杯中"); } } // 具体咖啡类:咖啡因咖啡 class CaffeineCoffee extends CoffeeTemplate { @Override void brewCoffee() { System.out.println("用沸水冲泡咖啡因咖啡"); } @Override void addCondiments() { System.out.println("加入牛奶和糖"); } } // 具体咖啡类:无咖啡因咖啡 class DecafCoffee extends CoffeeTemplate { @Override void brewCoffee() { System.out.println("用沸水冲泡无咖啡因咖啡"); } @Override void addCondiments() { System.out.println("加入柠檬"); } } // 测试类 public class TemplatePatternExample { public static void main(String[] args) { // 冲泡咖啡因咖啡 CoffeeTemplate caffeineCoffee = new CaffeineCoffee(); System.out.println("制作咖啡因咖啡:"); caffeineCoffee.makeCoffee(); System.out.println(); // 冲泡无咖啡因咖啡 CoffeeTemplate decafCoffee = new DecafCoffee(); System.out.println("制作无咖啡因咖啡:"); decafCoffee.makeCoffee(); } }
制作咖啡因咖啡:
烧开水
用沸水冲泡咖啡因咖啡
将咖啡倒入杯中
加入牛奶和糖
制作无咖啡因咖啡:
烧开水
用沸水冲泡无咖啡因咖啡
将咖啡倒入杯中
加入柠檬
事件驱动模式是一种设计模式,它基于事件的触发和响应机制来组织和管理程序的逻辑。在事件驱动模式中,系统中的各个组件通过订阅和发布事件的方式来进行通信和协作,当特定的事件发生时,订阅了该事件的组件会接收到通知并执行相应的处理逻辑。
结构
场景
优点
缺点
示例
import java.util.ArrayList; import java.util.List; // 定义事件类 class MyEvent { private String message; public MyEvent(String message) { this.message = message; } public String getMessage() { return message; } } // 定义事件监听器接口 interface MyEventListener { void onEvent(MyEvent event); } // 定义事件源类 class MyEventSource { private List<MyEventListener> listeners = new ArrayList<>(); // 注册事件监听器 public void addListener(MyEventListener listener) { listeners.add(listener); } // 触发事件 public void fireEvent(MyEvent event) { for (MyEventListener listener : listeners) { listener.onEvent(event); } } } // 示例:事件监听器的实现 class MyListener implements MyEventListener { @Override public void onEvent(MyEvent event) { System.out.println("Received event: " + event.getMessage()); } } public class Main { public static void main(String[] args) { // 创建事件源对象 MyEventSource eventSource = new MyEventSource(); // 创建事件监听器对象 MyEventListener listener = new MyListener(); // 注册事件监听器 eventSource.addListener(listener); // 触发事件 eventSource.fireEvent(new MyEvent("Hello, world!")); } }
Received event: Hello, world!
责任链模式是一种行为设计模式,它允许将请求沿着处理链传递,直到有一个处理者能够处理它为止。在责任链模式中,每个处理者都包含对下一个处理者的引用,当一个请求到达时,处理者可以选择处理请求或者将请求传递给下一个处理者。
结构
场景
优点
缺点
示例
// 请求类 class Request { private String content; public Request(String content) { this.content = content; } public String getContent() { return content; } } // 抽象处理器类 abstract class Handler { protected Handler nextHandler; public void setNextHandler(Handler nextHandler) { this.nextHandler = nextHandler; } public abstract void handleRequest(Request request); } // 具体处理器类 class ConcreteHandlerA extends Handler { @Override public void handleRequest(Request request) { if (request.getContent().equals("A")) { System.out.println("ConcreteHandlerA handles the request: " + request.getContent()); } else if (nextHandler != null) { nextHandler.handleRequest(request); } else { System.out.println("No handler can process the request."); } } } // 具体处理器类 class ConcreteHandlerB extends Handler { @Override public void handleRequest(Request request) { if (request.getContent().equals("B")) { System.out.println("ConcreteHandlerB handles the request: " + request.getContent()); } else if (nextHandler != null) { nextHandler.handleRequest(request); } else { System.out.println("No handler can process the request."); } } } // 具体处理器类 class ConcreteHandlerC extends Handler { @Override public void handleRequest(Request request) { if (request.getContent().equals("C")) { System.out.println("ConcreteHandlerC handles the request: " + request.getContent()); } else if (nextHandler != null) { nextHandler.handleRequest(request); } else { System.out.println("No handler can process the request."); } } } // 客户端类 public class Main { public static void main(String[] args) { // 创建处理器对象 Handler handlerA = new ConcreteHandlerA(); Handler handlerB = new ConcreteHandlerB(); Handler handlerC = new ConcreteHandlerC(); // 设置处理器的顺序 handlerA.setNextHandler(handlerB); handlerB.setNextHandler(handlerC); // 创建请求对象 Request request1 = new Request("A"); Request request2 = new Request("B"); Request request3 = new Request("C"); Request request4 = new Request("D"); // 处理请求 handlerA.handleRequest(request1); handlerA.handleRequest(request2); handlerA.handleRequest(request3); handlerA.handleRequest(request4); } }
ConcreteHandlerA handles the request: A
ConcreteHandlerB handles the request: B
ConcreteHandlerC handles the request: C
No handler can process the request.
中介者模式是一种行为设计模式,它允许对象之间通过一个中介者对象进行交互,而不直接相互引用。中介者模式促进了松耦合,因为它将对象之间的通信和协作集中在一个对象中,而不是分散在各个对象之间。
结构
场景
优点
缺点
示例
// 中介者接口 interface Mediator { void sendMessage(String message, Colleague colleague); } // 具体中介者类 class ConcreteMediator implements Mediator { private Colleague colleague1; private Colleague colleague2; public void setColleague1(Colleague colleague1) { this.colleague1 = colleague1; } public void setColleague2(Colleague colleague2) { this.colleague2 = colleague2; } @Override public void sendMessage(String message, Colleague colleague) { if (colleague == colleague1) { colleague2.receiveMessage(message); } else if (colleague == colleague2) { colleague1.receiveMessage(message); } } } // 抽象同事类 abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } public abstract void send(String message); public abstract void receiveMessage(String message); } // 具体同事类 class ConcreteColleague1 extends Colleague { public ConcreteColleague1(Mediator mediator) { super(mediator); } @Override public void send(String message) { System.out.println("ConcreteColleague1 sends message: " + message); mediator.sendMessage(message, this); } @Override public void receiveMessage(String message) { System.out.println("ConcreteColleague1 receives message: " + message); } } // 具体同事类 class ConcreteColleague2 extends Colleague { public ConcreteColleague2(Mediator mediator) { super(mediator); } @Override public void send(String message) { System.out.println("ConcreteColleague2 sends message: " + message); mediator.sendMessage(message, this); } @Override public void receiveMessage(String message) { System.out.println("ConcreteColleague2 receives message: " + message); } } // 客户端类 public class Main { public static void main(String[] args) { // 创建中介者对象 ConcreteMediator mediator = new ConcreteMediator(); // 创建具体同事对象 ConcreteColleague1 colleague1 = new ConcreteColleague1(mediator); ConcreteColleague2 colleague2 = new ConcreteColleague2(mediator); // 设置同事对象到中介者中 mediator.setColleague1(colleague1); mediator.setColleague2(colleague2); // 同事之间进行通信 colleague1.send("Hello, colleague2!"); colleague2.send("Hi, colleague1!"); } }
ConcreteColleague1 sends message: Hello, colleague2!
ConcreteColleague2 receives message: Hello, colleague2!
ConcreteColleague2 sends message: Hi, colleague1!
ConcreteColleague1 receives message: Hi, colleague1!
状态模式是一种行为设计模式,用于允许对象在其内部状态改变时改变其行为。它将对象的行为封装在不同的状态类中,并使得对象在不同状态下有不同的行为。这使得状态的切换不会影响到对象的行为,从而使得状态的改变更加灵活和可扩展。
结构
场景
优点
缺点
示例
// 状态接口 interface TrafficLightState { void handle(TrafficLight light); } // 具体状态类:红灯状态 class RedLightState implements TrafficLightState { @Override public void handle(TrafficLight light) { System.out.println("Red Light: Stop!"); light.setState(new GreenLightState()); } } // 具体状态类:绿灯状态 class GreenLightState implements TrafficLightState { @Override public void handle(TrafficLight light) { System.out.println("Green Light: Go!"); light.setState(new YellowLightState()); } } // 具体状态类:黄灯状态 class YellowLightState implements TrafficLightState { @Override public void handle(TrafficLight light) { System.out.println("Yellow Light: Prepare to stop!"); light.setState(new RedLightState()); } } // 上下文类 class TrafficLight { private TrafficLightState state; public TrafficLight() { // 初始状态为红灯 this.state = new RedLightState(); } public void setState(TrafficLightState state) { this.state = state; } public void change() { state.handle(this); } } // 客户端代码 public class Main { public static void main(String[] args) { TrafficLight trafficLight = new TrafficLight(); // 初始状态:红灯 trafficLight.change(); // 状态切换:红灯 -> 绿灯 trafficLight.change(); // 状态切换:绿灯 -> 黄灯 trafficLight.change(); // 状态切换:黄灯 -> 红灯 trafficLight.change(); } }
Red Light: Stop!
Green Light: Go!
Yellow Light: Prepare to stop!
Red Light: Stop!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。