引言
设计模式是软件开发中一种重要的实践,它们是经过时间考验和验证的解决方案,用于解决在软件设计过程中常见的特定问题。Java作为一门广泛使用的编程语言,其设计模式在软件开发中扮演着至关重要的角色。本文将深入解析Java的23种设计模式,并结合实战案例,帮助读者轻松掌握软件架构之道。
设计模式概述
Java设计模式分为三大类:
创建型模式
:解决对象的创建过程,使对象创建与使用分离。
结构型模式
:处理类或对象之间的组合,提高可复用性和可扩展性。
行为型模式
:处理对象之间的通信,提高模块间的解耦。
以下是每种设计模式的详细解析:
创建型模式
单例模式(Singleton)
:确保一个类只有一个实例,并提供一个全局访问点。
public class DatabasePool {
private static volatile DatabasePool instance;
private DatabasePool() {}
public static DatabasePool getInstance() {
if (instance == null) {
synchronized (DatabasePool.class) {
if (instance == null) {
instance = new DatabasePool();
}
}
}
return instance;
}
}
单例模式在配置管理、线程池、缓存系统等场景中非常有用。
工厂模式(Factory)
:通过统一接口创建对象,隐藏具体实现。
interface Logger {
void log(String msg);
}
class FileLogger implements Logger {
public void log(String msg) {
// 写入文件
}
}
class ConsoleLogger implements Logger {
public void log(String msg) {
// 写入控制台
}
}
class LoggerFactory {
public static Logger getLogger(String type) {
if (“file”.equalsIgnoreCase(type)) {
return new FileLogger();
} else if (“console”.equalsIgnoreCase(type)) {
return new ConsoleLogger();
}
return null;
}
}
抽象工厂模式(Abstract Factory)
:为创建一系列相关的或相互依赖的对象提供一个接口。
interface LoggerFactory {
Logger createLogger();
Database createDatabase();
}
class FileLoggerFactory implements LoggerFactory {
public Logger createLogger() {
return new FileLogger();
}
public Database createDatabase() {
return new FileDatabase();
}
}
建造者模式(Builder)
:将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。
public class Person {
private String name;
private int age;
private String address;
// 省略getter和setter方法
}
public class PersonBuilder {
private Person person = new Person();
public PersonBuilder setName(String name) {
person.name = name;
return this;
}
public PersonBuilder setAge(int age) {
person.age = age;
return this;
}
public PersonBuilder setAddress(String address) {
person.address = address;
return this;
}
public Person build() {
return person;
}
}
原型模式(Prototype)
:用原型实例指定创建对象的种类,并且通过复制这些原型创建新的对象。
public class Prototype implements Cloneable {
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
结构型模式
适配器模式(Adapter)
:将一个类的接口转换成客户希望的另一个接口。
interface Target {
void request();
}
class Adaptee {
public void specificRequest() {
// 实现特定请求
}
}
class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
public void request() {
adaptee.specificRequest();
}
}
桥接模式(Bridge)
:将抽象部分与它的实现部分分离,使它们都可以独立地变化。
abstract class Abstraction {
protected Implementation implementation;
public abstract void operation();
}
class RefinedAbstraction extends Abstraction {
public void operation() {
implementation.operationImpl();
}
}
class ConcreteImplementation implements Implementation {
public void operationImpl() {
// 实现操作
}
}
组合模式(Composite)
:将对象组合成树形结构以表示部分-整体层次结构。
abstract class Component {
public abstract void operation();
}
class Leaf extends Component {
public void operation() {
// 实现操作
}
}
class Composite extends Component {
private List
public void add(Component component) {
components.add(component);
}
public void operation() {
for (Component component : components) {
component.operation();
}
}
}
装饰器模式(Decorator)
:动态地给一个对象添加一些额外的职责。
abstract class Component {
public abstract void operation();
}
class ConcreteComponent extends Component {
public void operation() {
// 实现操作
}
}
class Decorator extends Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
外观模式(Facade)
:提供一个统一的接口,用来访问子系统中的一群接口。
interface SubsystemA {
void operationA();
}
interface SubsystemB {
void operationB();
}
class Facade {
private SubsystemA subsystemA;
private SubsystemB subsystemB;
public Facade() {
subsystemA = new SubsystemAImpl();
subsystemB = new SubsystemBImpl();
}
public void operation() {
subsystemA.operationA();
subsystemB.operationB();
}
}
享元模式(Flyweight)
:运用共享技术有效地支持大量细粒度的对象,减少内存中对象的数量。
class Flyweight {
public void operation(String extrinsicState) {
// 使用外部状态
}
}
class ConcreteFlyweight extends Flyweight {
private String intrinsicState;
public ConcreteFlyweight(String intrinsicState) {
this.intrinsicState = intrinsicState;
}
public void operation(String extrinsicState) {
// 使用内部状态和外部状态
}
}
代理模式(Proxy)
:为其他对象提供一种代理以控制对这个对象的访问。
interface Subject {
void request();
}
class RealSubject implements Subject {
public void request() {
// 实现请求
}
}
class Proxy implements Subject {
private RealSubject realSubject;
public Proxy(RealSubject realSubject) {
this.realSubject = realSubject;
}
public void request() {
// 代理请求
realSubject.request();
}
}
行为型模式
责任链模式(Chain of Responsibility)
:避免请求的发送者和接收者之间的耦合,将多对象有组织地连接成一条链,并沿着这条链传递请求。
interface Handler {
void handleRequest(Request request);
}
class ConcreteHandlerA implements Handler {
public void handleRequest(Request request) {
// 处理请求
}
}
class ConcreteHandlerB implements Handler {
public void handleRequest(Request request) {
// 处理请求
}
}
class ChainHandler implements Handler {
private Handler handler;
public ChainHandler(Handler handler) {
this.handler = handler;
}
public void handleRequest(Request request) {
handler.handleRequest(request);
}
}
命令模式(Command)
:封装请求,使其能延迟或取消执行。
interface Command {
void execute();
}
class ConcreteCommand implements Command {
private Receiver receiver;
public ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}
public void execute() {
receiver.action();
}
}
class Receiver {
public void action() {
// 实现操作
}
}
解释器模式(Interpreter)
:给定一个语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子。
interface Expression {
boolean interpret(String context);
}
class TerminalExpression implements Expression {
private String data;
public TerminalExpression(String data) {
this.data = data;
}
public boolean interpret(String context) {
return context.contains(data);
}
}
class OrExpression implements Expression {
private Expression expr1;
private Expression expr2;
public OrExpression(Expression expr1, Expression expr2) {
this.expr1 = expr1;
this.expr2 = expr2;
}
public boolean interpret(String context) {
return expr1.interpret(context) || expr2.interpret(context);
}
}
迭代器模式(Iterator)
:提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
interface Iterator {
boolean hasNext();
Object next();
}
class ConcreteIterator implements Iterator {
private List