JAVA最全设计模式(23种并附带示例)_java设计模式
一. 创建型模式:
定义: 创建型设计模式主要用于对象的创建过程,对对象的创建进行抽象,隐藏对象创建的具体逻辑。
1. 工厂方法模式:
定义一个用于创建对象的接口,但让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
// 产品接口
interface Shape {
void draw();
}
// 具体产品类
class Circle implements Shape {
@Override
public void draw() {
System.out.println(\"Drawing a circle\");
}
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println(\"Drawing a rectangle\");
}
}
// 工厂类
class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase(\"CIRCLE\")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase(\"RECTANGLE\")) {
return new Rectangle();
}
return null;
}
}
2.抽象工厂模式:
提供一个接口,用于创建相关或依赖对象的家族,而无需明确指定具体类。
// 抽象产品接口interface Color { void fill();}interface Shape { void draw();}// 具体产品类class Red implements Color { @Override public void fill() { System.out.println(\"Filling with red color\"); }}class Green implements Color { @Override public void fill() { System.out.println(\"Filling with green color\"); }}class Circle implements Shape { @Override public void draw() { System.out.println(\"Drawing a circle\"); }}class Rectangle implements Shape { @Override public void draw() { System.out.println(\"Drawing a rectangle\"); }}// 抽象工厂接口interface AbstractFactory { Color getColor(String color); Shape getShape(String shape);}// 具体工厂类class ShapeFactory implements AbstractFactory { @Override public Color getColor(String color) { return null; } @Override public Shape getShape(String shapeType) { if (shapeType == null) { return null; } if (shapeType.equalsIgnoreCase(\"CIRCLE\")) { return new Circle(); } else if (shapeType.equalsIgnoreCase(\"RECTANGLE\")) { return new Rectangle(); } return null; }}class ColorFactory implements AbstractFactory { @Override public Color getColor(String color) { if (color == null) { return null; } if (color.equalsIgnoreCase(\"RED\")) { return new Red(); } else if (color.equalsIgnoreCase(\"GREEN\")) { return new Green(); } return null; } @Override public Shape getShape(String shape) { return null; }}// 工厂创造器class FactoryProducer { public static AbstractFactory getFactory(String choice) { if (choice.equalsIgnoreCase(\"SHAPE\")) { return new ShapeFactory(); } else if (choice.equalsIgnoreCase(\"COLOR\")) { return new ColorFactory(); } return null; }}
3. 单例模式:
确保一个类只有一个实例,并提供一个全局访问点。
public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; }}
4. 建造者模式:
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
// 产品类class Meal { private String burger; private String drink; public void setBurger(String burger) { this.burger = burger; } public void setDrink(String drink) { this.drink = drink; } @Override public String toString() { return \"Burger: \" + burger + \", Drink: \" + drink; }}// 建造者接口interface MealBuilder { void buildBurger(); void buildDrink(); Meal getMeal();}// 具体建造者类class VegMealBuilder implements MealBuilder { private Meal meal; public VegMealBuilder() { this.meal = new Meal(); } @Override public void buildBurger() { meal.setBurger(\"Veg Burger\"); } @Override public void buildDrink() { meal.setDrink(\"Coke\"); } @Override public Meal getMeal() { return meal; }}// 指挥者类class MealDirector { private MealBuilder mealBuilder; public MealDirector(MealBuilder mealBuilder) { this.mealBuilder = mealBuilder; } public Meal constructMeal() { mealBuilder.buildBurger(); mealBuilder.buildDrink(); return mealBuilder.getMeal(); }}
5. 原型模式:
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
import java.util.Hashtable;// 抽象原型类abstract class Shape implements Cloneable { private String id; protected String type; abstract void draw(); public String getType() { return type; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Object clone() { Object clone = null; try { clone = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; }}// 具体原型类class Circle extends Shape { public Circle() { type = \"Circle\"; } @Override void draw() { System.out.println(\"Drawing a circle\"); }}class Rectangle extends Shape { public Rectangle() { type = \"Rectangle\"; } @Override void draw() { System.out.println(\"Drawing a rectangle\"); }}// 原型管理器class ShapeCache { private static Hashtable shapeMap = new Hashtable(); public static Shape getShape(String shapeId) { Shape cachedShape = shapeMap.get(shapeId); return (Shape) cachedShape.clone(); } public static void loadCache() { Circle circle = new Circle(); circle.setId(\"1\"); shapeMap.put(circle.getId(), circle); Rectangle rectangle = new Rectangle(); rectangle.setId(\"2\"); shapeMap.put(rectangle.getId(), rectangle); }}
二. 结构型模式:
定义:结构型设计模式主要用于处理类或对象的组合,通过组合类或对象形成更大的结构。
1. 适配器模式:
将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的类可以一起工作。
// 目标接口interface MediaPlayer { void play(String audioType, String fileName);}// 适配者接口interface AdvancedMediaPlayer { void playVlc(String fileName); void playMp4(String fileName);}// 具体适配者类class VlcPlayer implements AdvancedMediaPlayer { @Override public void playVlc(String fileName) { System.out.println(\"Playing vlc file. Name: \" + fileName); } @Override public void playMp4(String fileName) { // do nothing }}class Mp4Player implements AdvancedMediaPlayer { @Override public void playVlc(String fileName) { // do nothing } @Override public void playMp4(String fileName) { System.out.println(\"Playing mp4 file. Name: \" + fileName); }}// 适配器类class MediaAdapter implements MediaPlayer { AdvancedMediaPlayer advancedMusicPlayer; public MediaAdapter(String audioType) { if (audioType.equalsIgnoreCase(\"vlc\")) { advancedMusicPlayer = new VlcPlayer(); } else if (audioType.equalsIgnoreCase(\"mp4\")) { advancedMusicPlayer = new Mp4Player(); } } @Override public void play(String audioType, String fileName) { if (audioType.equalsIgnoreCase(\"vlc\")) { advancedMusicPlayer.playVlc(fileName); } else if (audioType.equalsIgnoreCase(\"mp4\")) { advancedMusicPlayer.playMp4(fileName); } }}// 具体类class AudioPlayer implements MediaPlayer { MediaAdapter mediaAdapter; @Override public void play(String audioType, String fileName) { if (audioType.equalsIgnoreCase(\"mp3\")) { System.out.println(\"Playing mp3 file. Name: \" + fileName); } else if (audioType.equalsIgnoreCase(\"vlc\") || audioType.equalsIgnoreCase(\"mp4\")) { mediaAdapter = new MediaAdapter(audioType); mediaAdapter.play(audioType, fileName); } else { System.out.println(\"Invalid media. \" + audioType + \" format not supported\"); } }}
2.装饰器模式:
动态地给一个对象添加一些额外的职责,就增加功能来说,装饰器模式比生成子类更为灵活。
// 组件接口interface Shape { void draw();}// 具体组件类class Circle implements Shape { @Override public void draw() { System.out.println(\"Shape: Circle\"); }}// 抽象装饰器类abstract class ShapeDecorator implements Shape { protected Shape decoratedShape; public ShapeDecorator(Shape decoratedShape) { this.decoratedShape = decoratedShape; } @Override public void draw() { decoratedShape.draw(); }}// 具体装饰器类class RedShapeDecorator extends ShapeDecorator { public RedShapeDecorator(Shape decoratedShape) { super(decoratedShape); } @Override public void draw() { decoratedShape.draw(); setRedBorder(decoratedShape); } private void setRedBorder(Shape decoratedShape) { System.out.println(\"Border Color: Red\"); }}
3.代理模式:
为其他对象提供一个代理或占位符,以控制对这个对象的访问。
// 接口interface Image { void display();}// 真实主题类class RealImage implements Image { private String fileName; public RealImage(String fileName) { this.fileName = fileName; loadFromDisk(fileName); } @Override public void display() { System.out.println(\"Displaying \" + fileName); } private void loadFromDisk(String fileName) { System.out.println(\"Loading \" + fileName); }}// 代理类class ProxyImage implements Image { private RealImage realImage; private String fileName; public ProxyImage(String fileName) { this.fileName = fileName; } @Override public void display() { if (realImage == null) { realImage = new RealImage(fileName); } realImage.display(); }}
4. 外观模式:
为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
// 子系统类class Rectangle { public void draw() { System.out.println(\"Rectangle::draw()\"); }}class Square { public void draw() { System.out.println(\"Square::draw()\"); }}class Circle { public void draw() { System.out.println(\"Circle::draw()\"); }}// 外观类class ShapeMaker { private Circle circle; private Rectangle rectangle; private Square square; public ShapeMaker() { circle = new Circle(); rectangle = new Rectangle(); square = new Square(); } public void drawCircle() { circle.draw(); } public void drawRectangle() { rectangle.draw(); } public void drawSquare() { square.draw(); }}
5. 桥接模式:
将抽象部分与它的实现部分分离,使它们都可以独立地变化。
// 实现化角色interface Color { void applyColor();}// 具体实现化角色class RedColor implements Color { @Override public void applyColor() { System.out.println(\"Applying red color\"); }}class GreenColor implements Color { @Override public void applyColor() { System.out.println(\"Applying green color\"); }}// 抽象化角色abstract class Shape { protected Color color; public Shape(Color color) { this.color = color; } abstract void draw();}// 扩展抽象化角色class Circle extends Shape { public Circle(Color color) { super(color); } @Override void draw() { System.out.print(\"Drawing a circle. \"); color.applyColor(); }}class Rectangle extends Shape { public Rectangle(Color color) { super(color); } @Override void draw() { System.out.print(\"Drawing a rectangle. \"); color.applyColor(); }}
6. 组合模式:
将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。
import java.util.ArrayList;import java.util.List;// 组件类abstract class Employee { protected String name; protected int salary; public Employee(String name, int salary) { this.name = name; this.salary = salary; } public abstract void add(Employee e); public abstract void remove(Employee e); public abstract void print();}// 树叶类class Developer extends Employee { public Developer(String name, int salary) { super(name, salary); } @Override public void add(Employee e) { // 树叶节点不能添加子节点 } @Override public void remove(Employee e) { // 树叶节点不能移除子节点 } @Override public void print() { System.out.println(\"
7. 享元模式:
运用共享技术有效地支持大量细粒度的对象。
import java.util.HashMap;// 享元接口interface Shape { void draw();}// 具体享元类class Circle implements Shape { private String color; private int x; private int y; private int radius; public Circle(String color) { this.color = color; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void setRadius(int radius) { this.radius = radius; } @Override public void draw() { System.out.println(\"Circle: Draw() [Color : \" + color + \", x : \" + x + \", y :\" + y + \", radius :\" + radius); }}// 享元工厂类class ShapeFactory { private static final HashMap circleMap = new HashMap(); public static Shape getCircle(String color) { Circle circle = (Circle) circleMap.get(color); if (circle == null) { circle = new Circle(color); circleMap.put(color, circle); System.out.println(\"Creating circle of color : \" + color); } return circle; }}
三. 行为型模式:
定义: 行为型设计模式主要用于处理对象之间的交互和职责分配,帮助对象之间更有效地通信和协作,从而实现更灵活、可维护的软件设计
1. 策略模式:
定义一系列的算法,把它们一个个封装起来,并且使它们可互相替换。此模式让算法的变化独立于使用算法的客户。
// 策略接口interface Strategy { int doOperation(int num1, int num2);}// 具体策略类 - 加法class OperationAdd implements Strategy { @Override public int doOperation(int num1, int num2) { return num1 + num2; }}// 具体策略类 - 减法class OperationSubtract implements Strategy { @Override public int doOperation(int num1, int num2) { return num1 - num2; }}// 上下文类class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public int executeStrategy(int num1, int num2) { return strategy.doOperation(num1, num2); }}// 测试代码public class StrategyPatternDemo { public static void main(String[] args) { Context context = new Context(new OperationAdd()); System.out.println(\"10 + 5 = \" + context.executeStrategy(10, 5)); context = new Context(new OperationSubtract()); System.out.println(\"10 - 5 = \" + context.executeStrategy(10, 5)); }}
2. 模板方法模式:
定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
// 抽象类,定义模板方法和基本方法abstract class Game { abstract void initialize(); abstract void startPlay(); abstract void endPlay(); // 模板方法 public final void play() { initialize(); startPlay(); endPlay(); }}// 具体子类 - 足球游戏class Football extends Game { @Override void initialize() { System.out.println(\"Football Game Initialized! Start playing.\"); } @Override void startPlay() { System.out.println(\"Football Game Started. Enjoy the game!\"); } @Override void endPlay() { System.out.println(\"Football Game Finished!\"); }}// 具体子类 - 篮球游戏class Basketball extends Game { @Override void initialize() { System.out.println(\"Basketball Game Initialized! Start playing.\"); } @Override void startPlay() { System.out.println(\"Basketball Game Started. Enjoy the game!\"); } @Override void endPlay() { System.out.println(\"Basketball Game Finished!\"); }}// 测试代码public class TemplatePatternDemo { public static void main(String[] args) { Game footballGame = new Football(); footballGame.play(); System.out.println(); Game basketballGame = new Basketball(); basketballGame.play(); }}
3. 观察者模式:
定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
import java.util.ArrayList;import java.util.List;// 主题接口interface Subject { void registerObserver(Observer o); void removeObserver(Observer o); void notifyObservers();}// 观察者接口interface Observer { void update(int state);}// 具体主题类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(state); } }}// 具体观察者类class ConcreteObserver implements Observer { private int observerState; @Override public void update(int state) { observerState = state; System.out.println(\"Observer state updated to: \" + observerState); }}// 测试代码public class ObserverPatternDemo { public static void main(String[] args) { ConcreteSubject subject = new ConcreteSubject(); ConcreteObserver observer1 = new ConcreteObserver(); ConcreteObserver observer2 = new ConcreteObserver(); subject.registerObserver(observer1); subject.registerObserver(observer2); subject.setState(10); }}
4. 迭代器模式:
提供一种方法顺序访问一个聚合对象中的各个元素,而又不需暴露该对象的内部表示。
// 迭代器接口interface Iterator { boolean hasNext(); Object next();}// 聚合接口interface Container { Iterator getIterator();}// 具体聚合类class NameRepository implements Container { public String[] names = {\"Robert\", \"John\", \"Julie\", \"Lora\"}; @Override public Iterator getIterator() { return new NameIterator(); } private class NameIterator implements Iterator { int index; @Override public boolean hasNext() { return index < names.length; } @Override public Object next() { if (this.hasNext()) { return names[index++]; } return null; } }}// 测试代码public class IteratorPatternDemo { public static void main(String[] args) { NameRepository namesRepository = new NameRepository(); for (Iterator iter = namesRepository.getIterator(); iter.hasNext(); ) { String name = (String) iter.next(); System.out.println(\"Name : \" + name); } }}
5. 责任链模式:
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
// 抽象处理者类abstract class AbstractLogger { public static final int INFO = 1; public static final int DEBUG = 2; public static final int ERROR = 3; protected int level; // 责任链中的下一个元素 protected AbstractLogger nextLogger; public void setNextLogger(AbstractLogger nextLogger) { this.nextLogger = nextLogger; } public void logMessage(int level, String message) { if (this.level <= level) { write(message); } if (nextLogger != null) { nextLogger.logMessage(level, message); } } abstract protected void write(String message);}// 具体处理者类 - 控制台日志记录器class ConsoleLogger extends AbstractLogger { public ConsoleLogger(int level) { this.level = level; } @Override protected void write(String message) { System.out.println(\"Standard Console::Logger: \" + message); }}// 具体处理者类 - 文件日志记录器class FileLogger extends AbstractLogger { public FileLogger(int level) { this.level = level; } @Override protected void write(String message) { System.out.println(\"File::Logger: \" + message); }}// 具体处理者类 - 错误日志记录器class ErrorLogger extends AbstractLogger { public ErrorLogger(int level) { this.level = level; } @Override protected void write(String message) { System.out.println(\"Error Console::Logger: \" + message); }}// 创建责任链class ChainPatternDemo { private static AbstractLogger getChainOfLoggers() { AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.ERROR); AbstractLogger fileLogger = new FileLogger(AbstractLogger.DEBUG); AbstractLogger consoleLogger = new ConsoleLogger(AbstractLogger.INFO); errorLogger.setNextLogger(fileLogger); fileLogger.setNextLogger(consoleLogger); return errorLogger; } public static void main(String[] args) { AbstractLogger loggerChain = getChainOfLoggers(); loggerChain.logMessage(AbstractLogger.INFO, \"This is an information.\"); System.out.println(); loggerChain.logMessage(AbstractLogger.DEBUG, \"This is a debug level information.\"); System.out.println(); loggerChain.logMessage(AbstractLogger.ERROR, \"This is an error information.\"); }}
6. 命令模式:
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化、对请求排队或记录请求日志,以及支持可撤销的操作。
// 命令接口interface Command { void execute();}// 具体命令类 - 开灯命令class LightOnCommand implements Command { private Light light; public LightOnCommand(Light light) { this.light = light; } @Override public void execute() { light.switchOn(); }}// 具体命令类 - 关灯命令class LightOffCommand implements Command { private Light light; public LightOffCommand(Light light) { this.light = light; } @Override public void execute() { light.switchOff(); }}// 接收者类 - 灯class Light { public void switchOn() { System.out.println(\"Light is on\"); } public void switchOff() { System.out.println(\"Light is off\"); }}// 调用者类 - 遥控器class RemoteControl { private Command command; public void setCommand(Command command) { this.command = command; } public void pressButton() { command.execute(); }}// 测试代码public class CommandPatternDemo { public static void main(String[] args) { Light light = new Light(); LightOnCommand lightOn = new LightOnCommand(light); LightOffCommand lightOff = new LightOffCommand(light); RemoteControl remote = new RemoteControl(); remote.setCommand(lightOn); remote.pressButton(); remote.setCommand(lightOff); remote.pressButton(); }}
7. 备忘录模式:
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
// 备忘录类class Memento { private String state; public Memento(String state) { this.state = state; } public String getState() { return state; }}// 原发器类class Originator { private String state; public void setState(String state) { this.state = state; } public String getState() { return state; } public Memento saveStateToMemento() { return new Memento(state); } public void getStateFromMemento(Memento memento) { state = memento.getState(); }}// 管理者类class CareTaker { private Memento memento; public void saveMemento(Memento memento) { this.memento = memento; } public Memento retrieveMemento() { return memento; }}// 测试代码public class MementoPatternDemo { public static void main(String[] args) { Originator originator = new Originator(); CareTaker careTaker = new CareTaker(); originator.setState(\"State #1\"); careTaker.saveMemento(originator.saveStateToMemento()); originator.setState(\"State #2\"); originator.getStateFromMemento(careTaker.retrieveMemento()); System.out.println(\"Current State: \" + originator.getState()); }}
8. 状态模式:
允许对象在内部状态改变时改变它的行为。对象看起来似乎修改了它的类。
// 状态接口interface State { void doAction(Context context);}// 具体状态类 - 开始状态class StartState implements State { @Override public void doAction(Context context) { System.out.println(\"Player is in start state\"); context.setState(this); } @Override public String toString() { return \"Start State\"; }}// 具体状态类 - 停止状态class StopState implements State { @Override public void doAction(Context context) { System.out.println(\"Player is in stop state\"); context.setState(this); } @Override public String toString() { return \"Stop State\"; }}// 上下文类class Context { private State state; public Context() { state = null; } public void setState(State state) { this.state = state; } public State getState() { return state; }}// 测试代码public class StatePatternDemo { public static void main(String[] args) { Context context = new Context(); StartState startState = new StartState(); startState.doAction(context); System.out.println(context.getState().toString()); StopState stopState = new StopState(); stopState.doAction(context); System.out.println(context.getState().toString()); }}
9. 访问者模式:
表示一个作用于某对象结构中的各元素的操作。它使你可以在不修改各元素的类的前提下定义作用于这些元素的新操作。
// 元素接口interface ComputerPart { void accept(ComputerPartVisitor visitor);}// 键盘类class Keyboard implements ComputerPart { @Override public void accept(ComputerPartVisitor visitor) { visitor.visit(this); }}// 鼠标类class Mouse implements ComputerPart { @Override public void accept(ComputerPartVisitor visitor) { visitor.visit(this); }}// 显示器类class Monitor implements ComputerPart { @Override public void accept(ComputerPartVisitor visitor) { visitor.visit(this); }}// 访问者接口interface ComputerPartVisitor { void visit(Keyboard keyboard); void visit(Mouse mouse); void visit(Monitor monitor);}// 价格统计访问者class PriceVisitor implements ComputerPartVisitor { private double totalPrice = 0; @Override public void visit(Keyboard keyboard) { // 假设键盘价格为 50 totalPrice += 50; } @Override public void visit(Mouse mouse) { // 假设鼠标价格为 30 totalPrice += 30; } @Override public void visit(Monitor monitor) { // 假设显示器价格为 500 totalPrice += 500; } public double getTotalPrice() { return totalPrice; }}// 信息展示访问者class InfoVisitor implements ComputerPartVisitor { @Override public void visit(Keyboard keyboard) { System.out.println(\"这是一个键盘\"); } @Override public void visit(Mouse mouse) { System.out.println(\"这是一个鼠标\"); } @Override public void visit(Monitor monitor) { System.out.println(\"这是一个显示器\"); }}// 客户端代码public class VisitorPatternDemo { public static void main(String[] args) { ComputerPart keyboard = new Keyboard(); ComputerPart mouse = new Mouse(); ComputerPart monitor = new Monitor(); // 使用价格统计访问者 PriceVisitor priceVisitor = new PriceVisitor(); keyboard.accept(priceVisitor); mouse.accept(priceVisitor); monitor.accept(priceVisitor); System.out.println(\"电脑硬件总价: \" + priceVisitor.getTotalPrice()); // 使用信息展示访问者 InfoVisitor infoVisitor = new InfoVisitor(); keyboard.accept(infoVisitor); mouse.accept(infoVisitor); monitor.accept(infoVisitor); }}
10. 中介者模式:
用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
// 中介者接口interface ChatMediator { void sendMessage(String message, User user); void addUser(User user);}// 具体中介者类class ChatMediatorImpl implements ChatMediator { private java.util.ArrayList users; public ChatMediatorImpl() { this.users = new java.util.ArrayList(); } @Override public void sendMessage(String message, User user) { for (User u : users) { if (u != user) { u.receive(message); } } } @Override public void addUser(User user) { this.users.add(user); }}// 同事类 - 用户abstract class User { protected ChatMediator mediator; protected String name; public User(ChatMediator med, String name) { this.mediator = med; this.name = name; } public abstract void send(String message); public abstract void receive(String message);}// 具体同事类 - 普通用户class ConcreteUser extends User { public ConcreteUser(ChatMediator med, String name) { super(med, name); } @Override public void send(String message) { System.out.println(this.name + \" sending message: \" + message); mediator.sendMessage(message, this); } @Override public void receive(String message) { System.out.println(this.name + \" received message: \" + message); }}// 测试代码public class MediatorPatternDemo { public static void main(String[] args) { ChatMediator mediator = new ChatMediatorImpl(); User user1 = new ConcreteUser(mediator, \"John\"); User user2 = new ConcreteUser(mediator, \"Jane\"); User user3 = new ConcreteUser(mediator, \"Bob\"); mediator.addUser(user1); mediator.addUser(user2); mediator.addUser(user3); user1.send(\"Hello, everyone!\"); }}
11. 解释器模式:
给定一个语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子
// 抽象表达式接口,定义了解释方法interface Expression { boolean interpret(Context context);}// 终结符表达式类,代表布尔变量class VariableExpression implements Expression { private String name; public VariableExpression(String name) { this.name = name; } // 根据上下文环境解释变量的值 @Override public boolean interpret(Context context) { return context.lookup(name); }}// 非终结符表达式类,代表逻辑与操作class AndExpression implements Expression { private Expression leftExpression; private Expression rightExpression; public AndExpression(Expression leftExpression, Expression rightExpression) { this.leftExpression = leftExpression; this.rightExpression = rightExpression; } // 解释逻辑与操作 @Override public boolean interpret(Context context) { return leftExpression.interpret(context) && rightExpression.interpret(context); }}import java.util.HashMap;import java.util.Map;// 上下文类,用于存储变量及其对应的值class Context { private Map variables = new HashMap(); public void assign(String name, boolean value) { variables.put(name, value); } public boolean lookup(String name) { return variables.getOrDefault(name, false); }}// 客户端代码public class InterpreterPatternSimpleDemo { public static void main(String[] args) { // 创建上下文对象 Context context = new Context(); // 为变量赋值 context.assign(\"x\", true); context.assign(\"y\", false); // 创建变量表达式 Expression x = new VariableExpression(\"x\"); Expression y = new VariableExpression(\"y\"); // 创建逻辑与表达式 Expression andExpression = new AndExpression(x, y); // 解释表达式并输出结果 boolean result = andExpression.interpret(context); System.out.println(\"表达式 x && y 的结果是: \" + result); }}