首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[教程]揭秘Java24种命令模式:实战解析与案例分析

发布于 2025-06-20 15:22:55
0
8

在Java编程中,设计模式是提高代码可重用性、可维护性和可扩展性的重要工具。命令模式(Command Pattern)是行为型设计模式之一,它将请求封装为一个对象,从而允许用户使用不同的请求、队列或日...

在Java编程中,设计模式是提高代码可重用性、可维护性和可扩展性的重要工具。命令模式(Command Pattern)是行为型设计模式之一,它将请求封装为一个对象,从而允许用户使用不同的请求、队列或日志请求,并支持可撤销的操作。本文将深入解析Java中的24种命令模式,并通过实战案例展示其应用。

1. 命令模式概述

命令模式是一种行为设计模式,它将请求封装为一个对象,从而允许用户使用不同的请求、队列或日志请求,并支持可撤销的操作。命令模式的主要目的是将调用操作的对象与知道如何实现该操作的对象解耦。

2. 命令模式的角色

命令模式涉及到以下角色:

  • 客户端(Client):创建一个具体命令(ConcreteCommand)对象并确定其接收者。
  • 命令(Command):声明了一个给所有具体命令类的抽象接口。
  • 具体命令(ConcreteCommand):定义一个接收者和行为之间的弱耦合;实现execute()方法,负责调用接收者的相应操作。
  • 请求者(Invoker):负责调用命令对象执行请求,相关的方法叫做行动方法。
  • 接收者(Receiver):负责具体实施和执行一个请求。

3. Java24种命令模式实战解析

3.1 单例模式(Singleton Pattern)

单例模式确保一个类只有一个实例,并提供一个全局访问点。

public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; }
}

3.2 工厂模式(Factory Pattern)

工厂模式创建一个用于创建对象的接口,让子类决定实例化哪一个类。

public interface CarFactory { Car createCar();
}
public class BMWFactory implements CarFactory { public Car createCar() { return new BMW(); }
}
public class BenzFactory implements CarFactory { public Car createCar() { return new Benz(); }
}

3.3 抽象工厂模式(Abstract Factory Pattern)

抽象工厂模式提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。

public interface CarFactory { Engine createEngine(); Transmission createTransmission();
}
public class BMWFactory implements CarFactory { public Engine createEngine() { return new BMWEngine(); } public Transmission createTransmission() { return new BMWTransmission(); }
}
public class BenzFactory implements CarFactory { public Engine createEngine() { return new BenzEngine(); } public Transmission createTransmission() { return new BenzTransmission(); }
}

3.4 建造者模式(Builder Pattern)

建造者模式将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。

public class Person { private String name; private int age; private String address; public static Builder builder() { return new Builder(); } public static class Builder { private String name; private int age; private String address; public Builder name(String name) { this.name = name; return this; } public Builder age(int age) { this.age = age; return this; } public Builder address(String address) { this.address = address; return this; } public Person build() { return new Person(this); } } private Person(Builder builder) { this.name = builder.name; this.age = builder.age; this.address = builder.address; }
}

3.5 原型模式(Prototype Pattern)

原型模式通过复制现有的实例来创建新的实例,从而避免直接实例化类。

public class Person implements Cloneable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }
}

3.6 适配器模式(Adapter Pattern)

适配器模式将一个类的接口转换成客户期望的另一个接口,使原本接口不兼容的类可以一起工作。

public interface Target { void request();
}
public class Adaptee { public void specificRequest() { System.out.println("Adaptee's specificRequest."); }
}
public class Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } @Override public void request() { adaptee.specificRequest(); }
}

3.7 桥接模式(Bridge Pattern)

桥接模式将抽象部分与实现部分分离,使它们都可以独立地变化。

public interface Abstraction { void operation();
}
public class RefinedAbstraction implements Abstraction { private Implementor implementor; public RefinedAbstraction(Implementor implementor) { this.implementor = implementor; } @Override public void operation() { implementor.operationImpl(); }
}
public interface Implementor { void operationImpl();
}
public class ConcreteImplementorA implements Implementor { @Override public void operationImpl() { System.out.println("ConcreteImplementorA's operationImpl."); }
}
public class ConcreteImplementorB implements Implementor { @Override public void operationImpl() { System.out.println("ConcreteImplementorB's operationImpl."); }
}

3.8 组合模式(Composite Pattern)

组合模式将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。

public abstract class Component { public abstract void operation();
}
public class Leaf extends Component { @Override public void operation() { System.out.println("Leaf operation."); }
}
public class Composite extends Component { private List children = new ArrayList<>(); @Override public void operation() { for (Component child : children) { child.operation(); } } public void add(Component child) { children.add(child); } public void remove(Component child) { children.remove(child); }
}

3.9 装饰器模式(Decorator Pattern)

装饰器模式动态地给一个对象添加一些额外的职责,就增加功能来说,装饰器模式比生成子类更为灵活。

public interface Component { void operation();
}
public class ConcreteComponent implements Component { @Override public void operation() { System.out.println("ConcreteComponent's operation."); }
}
public class Decorator implements Component { private Component component; public Decorator(Component component) { this.component = component; } @Override public void operation() { component.operation(); }
}
public class ConcreteDecoratorA extends Decorator { public ConcreteDecoratorA(Component component) { super(component); } @Override public void operation() { super.operation(); addedBehavior(); } private void addedBehavior() { System.out.println("ConcreteDecoratorA's addedBehavior."); }
}

3.10 外观模式(Facade Pattern)

外观模式提供了一个统一的接口,用来访问子系统中的一群接口,从而简化了客户端的调用。

public interface SubSystemA { void operationA();
}
public interface SubSystemB { void operationB();
}
public interface SubSystemC { void operationC();
}
public class Facade { private SubSystemA subSystemA; private SubSystemB subSystemB; private SubSystemC subSystemC; public Facade() { subSystemA = new SubSystemA(); subSystemB = new SubSystemB(); subSystemC = new SubSystemC(); } public void operation() { subSystemA.operationA(); subSystemB.operationB(); subSystemC.operationC(); }
}

3.11 享元模式(Flyweight Pattern)

享元模式通过共享尽可能多的相似对象来减少内存的使用。

public interface Flyweight { void operation(String extrinsicState);
}
public class ConcreteFlyweight implements Flyweight { private String intrinsicState; public ConcreteFlyweight(String intrinsicState) { this.intrinsicState = intrinsicState; } @Override public void operation(String extrinsicState) { System.out.println("Intrinsic State: " + intrinsicState + ", Extrinsic State: " + extrinsicState); }
}
public class FlyweightFactory { private Map flyweights = new HashMap<>(); public Flyweight getFlyweight(String key) { Flyweight flyweight = flyweights.get(key); if (flyweight == null) { flyweight = new ConcreteFlyweight(key); flyweights.put(key, flyweight); } return flyweight; }
}

3.12 代理模式(Proxy Pattern)

代理模式为其他对象提供一种代理以控制对这个对象的访问。

public interface Image { void display();
}
public class RealImage implements Image { private String fileName; public RealImage(String fileName) { this.fileName = fileName; loadImageFromDisk(); } @Override public void display() { System.out.println("Displaying " + fileName); } private void loadImageFromDisk() { System.out.println("Loading " + fileName + " from disk."); }
}
public 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(); }
}

3.13 责任链模式(Chain of Responsibility Pattern)

责任链模式使得多个对象都有机会处理请求,从而避免了请求发送者和接收者之间的耦合关系。

public interface Handler { void handle(Request request);
}
public class ConcreteHandlerA implements Handler { private Handler nextHandler; public void setNextHandler(Handler nextHandler) { this.nextHandler = nextHandler; } @Override public void handle(Request request) { if (request.getType() == Type.A) { System.out.println("ConcreteHandlerA handles request."); } else { if (nextHandler != null) { nextHandler.handle(request); } } }
}
public class ConcreteHandlerB implements Handler { private Handler nextHandler; public void setNextHandler(Handler nextHandler) { this.nextHandler = nextHandler; } @Override public void handle(Request request) { if (request.getType() == Type.B) { System.out.println("ConcreteHandlerB handles request."); } else { if (nextHandler != null) { nextHandler.handle(request); } } }
}
public class HandlerChain { private Handler handlerA; private Handler handlerB; public HandlerChain() { handlerA = new ConcreteHandlerA(); handlerB = new ConcreteHandlerB(); handlerA.setNextHandler(handlerB); } public void handleRequest(Request request) { handlerA.handle(request); }
}

3.14 解释器模式(Interpreter Pattern)

解释器模式为语言创建解释器,用于解释表达式。

public interface Expression { boolean interpret(String context);
}
public class TerminalExpression implements Expression { private String data; public TerminalExpression(String data) { this.data = data; } @Override public boolean interpret(String context) { return context.contains(data); }
}
public class OrExpression implements Expression { private Expression expr1; private Expression expr2; public OrExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } @Override public boolean interpret(String context) { return expr1.interpret(context) || expr2.interpret(context); }
}
public class AndExpression implements Expression { private Expression expr1; private Expression expr2; public AndExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } @Override public boolean interpret(String context) { return expr1.interpret(context) && expr2.interpret(context); }
}

3.15 迭代器模式(Iterator Pattern)

迭代器模式提供了一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

public interface Iterator { boolean hasNext(); Object next();
}
public class ListIterator implements Iterator { private List list; private int index; public ListIterator(List list) { this.list = list; this.index = 0; } @Override public boolean hasNext() { return index < list.size(); } @Override public Object next() { return list.get(index++); }
}

3.16 中介者模式(Mediator Pattern)

中介者模式定义一个对象来封装一组对象之间的交互,从而使对象之间的耦合松散,并使它们可以独立地改变。

public interface Mediator { void addColleague(Colleague colleague); void notify(String event, Colleague colleague);
}
public class ConcreteMediator implements Mediator { private List colleagues = new ArrayList<>(); @Override public void addColleague(Colleague colleague) { colleagues.add(colleague); } @Override public void notify(String event, Colleague colleague) { for (Colleague c : colleagues) { if (c != colleague) { c.receive(event); } } }
}
public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } public abstract void send(String event); public abstract void receive(String event);
}

3.17 备忘录模式(Memento Pattern)

备忘录模式用于保存一个对象的内部状态,以便可以在以后恢复它。

public class Memento { private String state; public Memento(String state) { this.state = state; } public String getState() { return state; }
}
public class Originator { private String state; public void setState(String state) { this.state = state; } public Memento saveStateToMemento() { return new Memento(state); } public void getStateFromMemento(Memento memento) { state = memento.getState(); }
}

3.18 观察者模式(Observer Pattern)

观察者模式定义对象间的一对多依赖关系,当一个对象改变状态时,所有依赖于它的对象都会得到通知并自动更新。

public interface Observer { void update(String message);
}
public class ConcreteObserver implements Observer { private String name; public ConcreteObserver(String name) { this.name = name; } @Override public void update(String message) { System.out.println(name + " received message: " + message); }
}
public interface Subject { void registerObserver(Observer observer); void removeObserver(Observer observer); void notifyObservers(String message);
}
public class ConcreteSubject implements Subject { private List observers = new ArrayList<>(); @Override public void registerObserver(Observer observer) { observers.add(observer); } @Override public void removeObserver(Observer observer) { observers.remove(observer); } @Override public void notifyObservers(String message) { for (Observer observer : observers) { observer.update(message); } }
}

3.19 状态模式(State Pattern)

状态模式允许一个对象在其内部状态改变时改变其行为。

public interface State { void handle();
}
public class ConcreteStateA implements State { @Override public void handle() { System.out.println("State A"); }
}
public class ConcreteStateB implements State { @Override public void handle() { System.out.println("State B"); }
}
public class Context { private State state; public void setState(State state) { this.state = state; } public void request() { state.handle(); }
}

3.20 空对象模式(Null Object Pattern)

空对象模式用于避免空对象引用,并简化代码。

public interface Service { void operation();
}
public class RealService implements Service { @Override public void operation() { System.out.println("RealService's operation."); }
}
public class NullService implements Service { @Override public void operation() { System.out.println("NullService's operation."); }
}

3.21 策略模式(Strategy Pattern)

策略模式定义一系列算法,把它们一个个封装起来,并使它们可以互相替换。

public interface Strategy { void execute();
}
public class ConcreteStrategyA implements Strategy { @Override public void execute() { System.out.println("ConcreteStrategyA's execute."); }
}
public class ConcreteStrategyB implements Strategy { @Override public void execute() { System.out.println("ConcreteStrategyB's execute."); }
}
public class Context { private Strategy strategy; public void setStrategy(Strategy strategy) { this.strategy = strategy; } public void executeStrategy() { strategy.execute(); }
}

3.22 模板方法模式(Template Method Pattern)

模板方法模式定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。

”`java public abstract class AbstractClass {

public final void templateMethod() { primitiveOperation1(); primitiveOperation2(); hook(); concreteOperation1(); concreteOperation2();
}
protected void primitiveOperation1() { System.out.println("AbstractClass - primitiveOperation1");
}
protected void primitiveOperation2() { System.out.println("AbstractClass - primitiveOperation2");
}
protected void hook() {
}
protected abstract void concreteOperation1();
protected abstract void concreteOperation2();

}

public class ConcreteClassA extends AbstractClass {

@Override
protected void concreteOperation1() { System.out.println("ConcreteClassA - concreteOperation1");
}
@Override
protected void concreteOperation2() { System.out.println("ConcreteClassA - concreteOperation2");
}

}

public class ConcreteClassB extends AbstractClass {

@Override
protected void concreteOperation1() { System.out.println("ConcreteClassB - concreteOperation1");
评论
一个月内的热帖推荐
csdn大佬
Lv.1普通用户

452398

帖子

22

小组

841

积分

赞助商广告