揭秘设计模式:五大分类解析,破解软件架构难题
引言
设计模式是软件开发中解决常见问题的通用解决方案。它们可以帮助开发者避免重复造轮子,提高代码的可重用性、可维护性和扩展性。设计模式按照不同的原则和目的可以分为五大类。本文将深入解析这五大分类,帮助读者更好地理解和使用设计模式,破解软件架构难题。
一、创建型模式
创建型模式关注对象的创建过程,主要目的是封装对象的创建逻辑,使得对象创建过程独立于使用对象的代码。以下是五大创建型模式:
1. 单例模式(Singleton)
单例模式确保一个类只有一个实例,并提供一个全局访问点。其核心是控制实例的创建,防止多次创建。
public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } 2. 工厂方法模式(Factory Method)
工厂方法模式定义一个接口用于创建对象,但让子类决定实例化哪一个类。其核心是分离实例化逻辑与对象使用逻辑。
public interface Factory { Product createProduct(); } public class ConcreteFactory implements Factory { public Product createProduct() { return new ConcreteProduct(); } } public class Product { // 产品类实现 } 3. 抽象工厂模式(Abstract Factory)
抽象工厂模式提供创建一系列相关或相互依赖对象的接口,而不需要指定它们具体的类。其核心是定义一个创建对象的接口,由子类决定实例化哪一个类。
public interface Factory { ProductA createProductA(); ProductB createProductB(); } public class ConcreteFactory implements Factory { public ProductA createProductA() { return new ConcreteProductA(); } public ProductB createProductB() { return new ConcreteProductB(); } } public class ProductA { // 产品A类实现 } public class ProductB { // 产品B类实现 } 4. 建造者模式(Builder)
建造者模式将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。其核心是将一个复杂对象的构建与它的表示分离。
public class Builder { public void buildPartA() { // 构建部分A } public void buildPartB() { // 构建部分B } public Product getResult() { return new Product(); } } public class Director { private Builder builder; public Director(Builder builder) { this.builder = builder; } public void construct() { builder.buildPartA(); builder.buildPartB(); } } public class Product { // 产品类实现 } 5. 原型模式(Prototype)
原型模式通过复制现有的实例来创建新的实例,而不需要通过构造函数。其核心是直接复制现有对象来创建新对象。
public class Prototype implements Cloneable { @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } 二、结构型模式
结构型模式关注类和对象的组合,主要目的是将接口与实现解耦,使代码结构更清晰。以下是五大结构型模式:
1. 适配器模式(Adapter)
适配器模式将一个类的接口转换成客户期望的另一个接口,使原本接口不兼容的类可以一起工作。其核心是提供一个中间接口,使得原本接口不兼容的类可以一起工作。
public interface Target { void request(); } public class Adaptee { public void specificRequest() { // 原有接口 } } public class Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } public void request() { adaptee.specificRequest(); } } 2. 代理模式(Proxy)
代理模式为其他对象提供一种代理以控制对这个对象的访问。其核心是提供一个代理对象,用来控制对目标对象的访问。
public interface Subject { void request(); } public class RealSubject implements Subject { public void request() { // 实际操作 } } public class Proxy implements Subject { private RealSubject realSubject; public Proxy(RealSubject realSubject) { this.realSubject = realSubject; } public void request() { // 在这里可以添加一些预处理逻辑 realSubject.request(); // 在这里可以添加一些后处理逻辑 } } 3. 桥接模式(Bridge)
桥接模式将抽象部分与实现部分分离,使它们都可以独立地变化。其核心是定义一个抽象类和一个实现类,通过组合的方式将它们连接起来。
public abstract class Abstraction { protected Implementor implementor; public Abstraction(Implementor implementor) { this.implementor = implementor; } public abstract void operation(); } public class RefinedAbstraction extends Abstraction { public void operation() { // 使用实现类的方法 implementor.operationImpl(); } } public interface Implementor { void operationImpl(); } public class ConcreteImplementorA implements Implementor { public void operationImpl() { // 实现细节 } } 4. 组合模式(Composite)
组合模式将对象组合成树形结构以表示部分整体层次结构,使得用户对单个对象和组合对象的使用具有一致性。其核心是将对象组合成树形结构,并统一使用。
public abstract class Component { public abstract void operation(); } public class Leaf extends Component { public void operation() { // 叶子节点操作 } } public class Composite extends Component { private List<Component> children = new ArrayList<>(); public void add(Component child) { children.add(child); } public void remove(Component child) { children.remove(child); } public void operation() { for (Component child : children) { child.operation(); } } } 5. 装饰器模式(Decorator)
装饰器模式动态地给一个对象添加一些额外的职责,而不改变其接口。其核心是动态地给对象添加一些额外的职责。
public interface Component { void operation(); } public class ConcreteComponent implements Component { public void operation() { // 原有操作 } } public class Decorator implements Component { private Component component; public Decorator(Component component) { this.component = component; } public void operation() { component.operation(); // 增加新功能 } } 三、行为型模式
行为型模式主要关注对象之间的交互和通信,以及如何协调对象间的职责。以下是五大行为型模式:
1. 职责链模式(Chain of Responsibility)
职责链模式将请求的发送者和接收者解耦,使多个对象都有机会处理请求,从而实现请求的传递和处理。其核心是将请求的发送者和接收者解耦,并使多个对象都有机会处理请求。
public interface Handler { void handle(Request request); } public class ConcreteHandlerA implements Handler { private Handler nextHandler; public ConcreteHandlerA(Handler nextHandler) { this.nextHandler = nextHandler; } public void handle(Request request) { if (request.type() == TYPE_A) { // 处理请求 } else { nextHandler.handle(request); } } } public class ConcreteHandlerB implements Handler { public void handle(Request request) { if (request.type() == TYPE_B) { // 处理请求 } } } public class Request { private int type; public Request(int type) { this.type = type; } public int type() { return type; } } 2. 命令模式(Command)
命令模式将请求封装为一个对象,从而允许用户使用不同的请求、队列或日志来参数化其他对象。其核心是将请求封装为一个对象,并支持可撤销的操作。
public interface Command { void execute(); } public class ConcreteCommand implements Command { private Receiver receiver; public ConcreteCommand(Receiver receiver) { this.receiver = receiver; } public void execute() { receiver.action(); } } public class Receiver { public void action() { // 执行请求 } } public class Invoker { private Command command; public void setCommand(Command command) { this.command = command; } public void executeCommand() { command.execute(); } } 3. 解释器模式(Interpreter)
解释器模式定义语言的文法,并创建一个解释器来解释语言中的句子。其核心是定义语言的文法,并创建一个解释器来解释语言中的句子。
public interface Expression { boolean interpret(String context); } public class TerminalExpression implements Expression { private String data; public TerminalExpression(String data) { this.data = data; } public boolean interpret(String context) { return context.contains(data); } } public class NonTerminalExpression implements Expression { private List<Expression> expressions = new ArrayList<>(); public void add(Expression expression) { expressions.add(expression); } public boolean interpret(String context) { for (Expression expression : expressions) { if (!expression.interpret(context)) { return false; } } return true; } } public class Context { private String data; public Context(String data) { this.data = data; } public String getData() { return data; } } 4. 迭代器模式(Iterator)
迭代器模式提供一种方法顺序访问一个聚合对象中各个元素,而不需要暴露该对象的内部表示。其核心是提供一种方法顺序访问一个聚合对象中各个元素,而不需要暴露该对象的内部表示。
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; } public boolean hasNext() { return index < list.size(); } public Object next() { return list.get(index++); } } 5. 中介者模式(Mediator)
中介者模式定义一个对象来封装一组对象之间的交互,使对象之间不需要显式地相互引用,从而降低它们之间的耦合。其核心是定义一个对象来封装一组对象之间的交互,并降低它们之间的耦合。
public interface Mediator { void send(String message, Colleague colleague); } public class ConcreteMediator implements Mediator { private Colleague colleagueA; private Colleague colleagueB; public ConcreteMediator(Colleague colleagueA, Colleague colleagueB) { this.colleagueA = colleagueA; this.colleagueB = colleagueB; } public void send(String message, Colleague sender) { if (sender == colleagueA) { colleagueB.receive(message); } else { colleagueA.receive(message); } } } public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } public abstract void send(String message); public abstract void receive(String message); } 四、总结
设计模式是软件开发中的宝贵财富,合理运用设计模式可以提高代码质量,降低维护成本。本文详细解析了五大分类的设计模式,包括创建型、结构型、行为型和中介者模式。通过学习这些模式,开发者可以更好地解决软件架构难题,提高代码的可读性、可维护性和可扩展性。在实际开发过程中,根据具体需求选择合适的设计模式,是提升开发效率的关键。
支付宝扫一扫
微信扫一扫