深入探讨Java设计模式:构建灵活而可维护的代码
设计模式是在软件设计中,经过反复验证,以解决特定问题的最佳实践的经验总结。在Java中,设计模式是一种强大的工具,用于构建可扩展、灵活且易于维护的代码。本文将深入讨论一些常见的Java设计模式,以及它们在实际应用中的应用场景。
1. 单例模式(Singleton Pattern)
单例模式确保一个类只有一个实例,并提供一个全局访问点。这在需要共享资源的情况下非常有用,比如数据库连接、配置管理等。
public class Singleton {private static Singleton instance;private Singleton() {}public static Singleton getInstance() {if (instance == null) {instance = new Singleton();}return instance;}
}
2. 工厂模式(Factory Pattern)
工厂模式用于创建对象,通过定义一个接口或抽象类,然后由子类决定实例化哪一个类。这有助于封装对象的创建逻辑,提高代码的可维护性。
public interface Shape {void draw();
}public class Circle implements Shape {@Overridepublic void draw() {System.out.println("Draw a circle");}
}public class Square implements Shape {@Overridepublic void draw() {System.out.println("Draw a square");}
}public class ShapeFactory {public Shape getShape(String shapeType) {if (shapeType == null) {return null;}if (shapeType.equalsIgnoreCase("CIRCLE")) {return new Circle();} else if (shapeType.equalsIgnoreCase("SQUARE")) {return new Square();}return null;}
}
3. 观察者模式(Observer Pattern)
观察者模式定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都得到通知并自动更新。
import java.util.ArrayList;
import java.util.List;// 主题接口
public interface Subject {void addObserver(Observer observer);void removeObserver(Observer observer);void notifyObservers();
}// 具体主题
public class ConcreteSubject implements Subject {private List<Observer> observers = new ArrayList<>();@Overridepublic void addObserver(Observer observer) {observers.add(observer);}@Overridepublic void removeObserver(Observer observer) {observers.remove(observer);}@Overridepublic void notifyObservers() {for (Observer observer : observers) {observer.update();}}
}// 观察者接口
public interface Observer {void update();
}// 具体观察者
public class ConcreteObserver implements Observer {@Overridepublic void update() {System.out.println("Update received");}
}
4. 策略模式(Strategy Pattern)
策略模式定义了一族算法,将每个算法都封装起来,并且使它们之间可以互换。这使得算法可以独立于客户端而变化。
// 策略接口
public interface PaymentStrategy {void pay(int amount);
}// 具体策略
public class CreditCardPayment implements PaymentStrategy {@Overridepublic void pay(int amount) {System.out.println("Paid with credit card: " + amount);}
}public class PayPalPayment implements PaymentStrategy {@Overridepublic void pay(int amount) {System.out.println("Paid with PayPal: " + amount);}
}// 环境类
public class ShoppingCart {private PaymentStrategy paymentStrategy;public void setPaymentStrategy(PaymentStrategy paymentStrategy) {this.paymentStrategy = paymentStrategy;}public void checkout(int amount) {paymentStrategy.pay(amount);}
}
5. 模板方法模式(Template Method Pattern)
模板方法模式定义了一个算法的骨架,将一些步骤延迟到子类中实现。这样一来,子类可以在不改变算法结构的情况下重新定义算法的某些步骤。
// 抽象类
public abstract class Game {abstract void initialize();abstract void startPlay();abstract void endPlay();// 模板方法public final void play() {initialize();startPlay();endPlay();}
}// 具体类
public class Cricket extends Game {@Overridevoid initialize() {System.out.println("Cricket Game Initialized! Start playing.");}@Overridevoid startPlay() {System.out.println("Cricket Game Started. Enjoy the game!");}@Overridevoid endPlay() {System.out.println("Cricket Game Finished!");}
}public class Football extends Game {@Overridevoid initialize() {System.out.println("Football Game Initialized! Start playing.");}@Overridevoid startPlay() {System.out.println("Football Game Started. Enjoy the game!");}@Overridevoid endPlay() {System.out.println("Football Game Finished!");}
}
6. 装饰器模式(Decorator Pattern)
装饰器模式允许你通过将对象放入包装类中来给对象动态地添加新的功能。这种模式是继承关系的一个替代方案,它使得你可以灵活地扩展一个对象的功能。
// 抽象组件
public interface Shape {void draw();
}// 具体组件
public class Circle implements Shape {@Overridepublic void draw() {System.out.println("Draw a circle");}
}// 抽象装饰器
public abstract class ShapeDecorator implements Shape {protected Shape decoratedShape;public ShapeDecorator(Shape decoratedShape) {this.decoratedShape = decoratedShape;}public void draw() {decoratedShape.draw();}
}// 具体装饰器
public class RedShapeDecorator extends ShapeDecorator {public RedShapeDecorator(Shape decoratedShape) {super(decoratedShape);}@Overridepublic void draw() {decoratedShape.draw();setRedBorder(decoratedShape);}private void setRedBorder(Shape decoratedShape){System.out.println("Border Color: Red");}
}
7. 适配器模式(Adapter Pattern)
适配器模式允许接口不兼容的类能够协同工作。它通常用于让现有类与其他类一起工作,而无需修改其源代码。
// 目标接口
public interface Target {void request();
}// 具体目标
public class ConcreteTarget implements Target {@Overridepublic void request() {System.out.println("Target's request");}
}// 适配器
public class Adapter implements Target {private Adaptee adaptee;public Adapter(Adaptee adaptee) {this.adaptee = adaptee;}@Overridepublic void request() {adaptee.specificRequest();}
}// 源类
public class Adaptee {public void specificRequest() {System.out.println("Adaptee's specific request");}
}
8. 命令模式(Command Pattern)
命令模式将请求封装成对象,这可以让你参数化其他对象,队列化请求、以及支持可撤销的操作。
// 命令接口
public interface Command {void execute();
}// 具体命令
public class ConcreteCommand implements Command {private Receiver receiver;public ConcreteCommand(Receiver receiver) {this.receiver = receiver;}@Overridepublic void execute() {receiver.action();}
}// 接收者
public class Receiver {public void action() {System.out.println("Receiver's action");}
}// 调用者
public class Invoker {private Command command;public Invoker(Command command) {this.command = command;}public void invoke() {command.execute();}
}
9. 责任链模式(Chain of Responsibility Pattern)
责任链模式允许你将请求沿着处理者链进行传递,直到有一个处理者能够处理它。这种模式常用于系统中有多个对象可以处理同一请求的情况。
// 处理者接口
public interface Handler {void handleRequest(int request);void setNextHandler(Handler nextHandler);
}// 具体处理者
public class ConcreteHandler1 implements Handler {private Handler nextHandler;@Overridepublic void handleRequest(int request) {if (request < 10) {System.out.println("ConcreteHandler1 handles request: " + request);} else if (nextHandler != null) {nextHandler.handleRequest(request);}}@Overridepublic void setNextHandler(Handler nextHandler) {this.nextHandler = nextHandler;}
}public class ConcreteHandler2 implements Handler {private Handler nextHandler;@Overridepublic void handleRequest(int request) {if (request >= 10 && request < 20) {System.out.println("ConcreteHandler2 handles request: " + request);} else if (nextHandler != null) {nextHandler.handleRequest(request);}}@Overridepublic void setNextHandler(Handler nextHandler) {this.nextHandler = nextHandler;}
}
10. 迭代器模式(Iterator Pattern)
迭代器模式提供了一种顺序访问集合对象元素的方法,而不暴露集合的内部表示。通过使用迭代器模式,我们可以以一种统一的方式访问不同类型的集合。
// 迭代器接口
public interface Iterator {boolean hasNext();Object next();
}// 聚合接口
public interface Container {Iterator getIterator();
}// 具体迭代器
public class ConcreteIterator implements Iterator {private Object[] elements;private int position = 0;public ConcreteIterator(Object[] elements) {this.elements = elements;}@Overridepublic boolean hasNext() {return position < elements.length;}@Overridepublic Object next() {if (this.hasNext()) {return elements[position++];}return null;}
}// 具体聚合
public class ConcreteContainer implements Container {private Object[] elements;public ConcreteContainer(Object[] elements) {this.elements = elements;}@Overridepublic Iterator getIterator() {return new ConcreteIterator(elements);}
}
11. 代理模式(Proxy Pattern)
代理模式用于控制对对象的访问,充当被访问对象的中间层。它可以在不改变原始对象的情况下,增加额外的逻辑,比如延迟加载、权限控制等。
// 主题接口
public interface RealSubject {void request();
}// 具体主题
public class RealSubjectImpl implements RealSubject {@Overridepublic void request() {System.out.println("RealSubject handles request");}
}// 代理类
public class Proxy implements RealSubject {private RealSubjectImpl realSubject;@Overridepublic void request() {if (realSubject == null) {realSubject = new RealSubjectImpl();}// 可以在此处添加额外逻辑System.out.println("Proxy handles request");realSubject.request();}
}
12. 享元模式(Flyweight Pattern)
享元模式旨在减少对象的数量,以节省内存和提高性能。它通过共享相似对象之间的部分状态,以减小对象的存储开销。
// 享元接口
public interface Flyweight {void operation();
}// 具体享元
public class ConcreteFlyweight implements Flyweight {private String intrinsicState;public ConcreteFlyweight(String intrinsicState) {this.intrinsicState = intrinsicState;}@Overridepublic void operation() {System.out.println("ConcreteFlyweight with intrinsic state: " + intrinsicState);}
}// 享元工厂
public class FlyweightFactory {private Map<String, Flyweight> flyweights = new HashMap<>();public Flyweight getFlyweight(String key) {if (!flyweights.containsKey(key)) {flyweights.put(key, new ConcreteFlyweight(key));}return flyweights.get(key);}
}
13. 访问者模式(Visitor Pattern)
访问者模式将算法与对象结构分离,使得能够在不修改原始类的情况下添加新的操作。这对于处理复杂的对象结构,同时保持类的封装性非常有用。
// 元素接口
public interface Element {void accept(Visitor visitor);
}// 具体元素
public class ConcreteElement implements Element {@Overridepublic void accept(Visitor visitor) {visitor.visit(this);}
}// 访问者接口
public interface Visitor {void visit(ConcreteElement element);
}// 具体访问者
public class ConcreteVisitor implements Visitor {@Overridepublic void visit(ConcreteElement element) {System.out.println("Visitor visits ConcreteElement");}
}
14. 状态模式(State Pattern)
状态模式允许一个对象在其内部状态改变时改变它的行为。通过将状态抽象成独立的类,使得对象的状态可以独立于其行为而变化。
// 状态接口
public interface State {void handle(Context context);
}// 具体状态
public class ConcreteStateA implements State {@Overridepublic void handle(Context context) {System.out.println("Handling state A");context.setState(new ConcreteStateB());}
}public class ConcreteStateB implements State {@Overridepublic void handle(Context context) {System.out.println("Handling state B");context.setState(new ConcreteStateA());}
}// 上下文
public class Context {private State state;public Context(State state) {this.state = state;}public void setState(State state) {this.state = state;}public void request() {state.handle(this);}
}
15. 备忘录模式(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 String getState() {return state;}public Memento saveStateToMemento() {return new Memento(state);}public void getStateFromMemento(Memento memento) {state = memento.getState();}
}// 负责人
public class Caretaker {private List<Memento> mementos = new ArrayList<>();public void addMemento(Memento memento) {mementos.add(memento);}public Memento getMemento(int index) {return mementos.get(index);}
}
16. 桥接模式(Bridge Pattern)
桥接模式将抽象部分与它的实现部分分离,使它们可以独立变化。这种模式主要用于处理具有多维度变化的复杂系统,将系统抽象与实现解耦,使得系统更加灵活。
// 实现者接口
public interface Implementor {void operationImpl();
}// 具体实现者
public class ConcreteImplementorA implements Implementor {@Overridepublic void operationImpl() {System.out.println("Concrete Implementor A");}
}public class ConcreteImplementorB implements Implementor {@Overridepublic void operationImpl() {System.out.println("Concrete Implementor B");}
}// 抽象部分
public abstract class Abstraction {protected Implementor implementor;public Abstraction(Implementor implementor) {this.implementor = implementor;}public abstract void operation();
}// 具体抽象部分
public class RefinedAbstraction extends Abstraction {public RefinedAbstraction(Implementor implementor) {super(implementor);}@Overridepublic void operation() {System.out.print("Refined Abstraction - ");implementor.operationImpl();}
}
17. 组合模式(Composite Pattern)
组合模式允许客户以一致的方式处理单个对象和对象组合。它通过将对象组合成树形结构来表示部分-整体层次结构,从而使得客户可以统一地处理单个对象和组合对象。
// 组件接口
public interface Component {void operation();
}// 叶子节点
public class Leaf implements Component {@Overridepublic void operation() {System.out.println("Leaf operation");}
}// 容器节点
public class Composite implements Component {private List<Component> components = new ArrayList<>();public void add(Component component) {components.add(component);}public void remove(Component component) {components.remove(component);}@Overridepublic void operation() {System.out.println("Composite operation");for (Component component : components) {component.operation();}}
}
18. 命令查询职责隔离(CQRS)
CQRS是一种软件架构模式,它将命令和查询的职责分开。通过独立处理读取和写入操作,CQRS提供了更大的灵活性和性能优势。
// 命令处理器
public class CommandHandler {public void handleCommand(Command command) {// 处理命令}
}// 查询处理器
public class QueryHandler {public Result handleQuery(Query query) {// 处理查询return new Result();}
}// 命令
public class Command {// 命令的属性和方法
}// 查询
public class Query {// 查询的属性和方法
}// 查询结果
public class Result {// 结果的属性和方法
}
19. 观察者模式(Observer Pattern)在事件驱动中的应用
观察者模式在事件驱动系统中得到广泛应用。当一个事件发生时,所有注册的观察者都会被通知并执行相应的操作,从而实现了松耦合和更好的可维护性。
import java.util.ArrayList;
import java.util.List;// 主题
public class Subject {private List<Observer> observers = new ArrayList<>();public void addObserver(Observer observer) {observers.add(observer);}public void removeObserver(Observer observer) {observers.remove(observer);}public void notifyObservers() {for (Observer observer : observers) {observer.update();}}
}// 观察者
public interface Observer {void update();
}// 具体观察者
public class ConcreteObserver implements Observer {@Overridepublic void update() {System.out.println("ConcreteObserver updates");}
}
20. 亨元模式(Flyweight Pattern)在图形绘制中的应用
亨元模式用于共享细粒度的对象,以减小系统中对象的数量。在图形绘制中,亨元模式可以用于共享相同颜色、形状等属性的图形对象,提高系统的性能和资源利用率。
// 亨元接口
public interface Flyweight {void draw(int x, int y);
}// 具体亨元
public class ConcreteFlyweight implements Flyweight {private String color;public ConcreteFlyweight(String color) {this.color = color;}@Overridepublic void draw(int x, int y) {System.out.println("Drawing a " + color + " shape at (" + x + ", " + y + ")");}
}// 亨元工厂
public class FlyweightFactory {private Map<String, Flyweight> flyweights = new HashMap<>();public Flyweight getFlyweight(String color) {if (!flyweights.containsKey(color)) {flyweights.put(color, new ConcreteFlyweight(color));}return flyweights.get(color);}
}