网站首页 > java教程 正文
设计模式是软件设计中常见问题的典型解决方案,它们是可以重复使用的设计模板。GoF(Gang of Four)提出的23种经典设计模式可分为三大类:创建型、结构型和行为型。
创建型模式关注于对象的创建,提供了更灵活的对象创建方式。
结构型模式关注如何将类或对象组合成更大的结构,以便更好地实现功能。
行为型模式关注对象之间的沟通和职责分配。
一、创建型模式 (5种)
1. 单例模式 (Singleton)
目的:确保一个类只有一个实例,并提供全局访问点。
java
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2. 工厂方法模式 (Factory Method)
目的:定义一个创建对象的接口,但让子类决定实例化哪个类。
java
public interface Product {
void use();
}
public class ConcreteProduct implements Product {
public void use() {
System.out.println("Using ConcreteProduct");
}
}
public abstract class Creator {
public abstract Product factoryMethod();
}
public class ConcreteCreator extends Creator {
public Product factoryMethod() {
return new ConcreteProduct();
}
}
3. 抽象工厂模式 (Abstract Factory)
目的:提供一个接口,用于创建相关或依赖对象的家族,而不需要指定具体类。
java
public interface AbstractFactory {
ProductA createProductA();
ProductB createProductB();
}
public class ConcreteFactory1 implements AbstractFactory {
public ProductA createProductA() {
return new ProductA1();
}
public ProductB createProductB() {
return new ProductB1();
}
}
4. 建造者模式 (Builder)
目的:将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。
java
public class Product {
private String part1;
private String part2;
// setters and getters
}
public interface Builder {
void buildPart1();
void buildPart2();
Product getResult();
}
public class Director {
public Product construct(Builder builder) {
builder.buildPart1();
builder.buildPart2();
return builder.getResult();
}
}
5. 原型模式 (Prototype)
目的:通过复制现有对象来创建新对象,而不是新建。
java
public class Prototype implements Cloneable {
@Override
public Prototype clone() {
try {
return (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}
二、结构型模式 (7种)
6. 适配器模式 (Adapter)
目的:将一个类的接口转换成客户希望的另一个接口。
java
public interface Target {
void request();
}
public class Adaptee {
public void specificRequest() {
System.out.println("Specific request");
}
}
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
public void request() {
adaptee.specificRequest();
}
}
7. 桥接模式 (Bridge)
目的:将抽象部分与实现部分分离,使它们可以独立变化。
java
public interface Implementor {
void operationImpl();
}
public abstract class Abstraction {
protected Implementor implementor;
public Abstraction(Implementor implementor) {
this.implementor = implementor;
}
public abstract void operation();
}
8. 组合模式 (Composite)
目的:将对象组合成树形结构以表示"部分-整体"的层次结构。
java
public interface Component {
void operation();
}
public class Leaf implements Component {
public void operation() {
System.out.println("Leaf operation");
}
}
public class Composite implements Component {
private List<Component> children = new ArrayList<>();
public void add(Component component) {
children.add(component);
}
public void operation() {
for (Component child : children) {
child.operation();
}
}
}
9. 装饰器模式 (Decorator)
目的:动态地给一个对象添加一些额外的职责。
java
public interface Component {
void operation();
}
public class ConcreteComponent implements Component {
public void operation() {
System.out.println("ConcreteComponent operation");
}
}
public abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
10. 外观模式 (Facade)
目的:为子系统中的一组接口提供一个一致的界面。
java
public class SubSystemA {
public void operationA() {
System.out.println("Operation A");
}
}
public class Facade {
private SubSystemA subSystemA = new SubSystemA();
public void operation() {
subSystemA.operationA();
// 调用其他子系统方法
}
}
11. 享元模式 (Flyweight)
目的:运用共享技术有效地支持大量细粒度的对象。
java
public interface Flyweight {
void operation(String extrinsicState);
}
public class ConcreteFlyweight implements Flyweight {
private String intrinsicState;
public ConcreteFlyweight(String intrinsicState) {
this.intrinsicState = intrinsicState;
}
public void operation(String extrinsicState) {
System.out.println("Intrinsic: " + intrinsicState + ", Extrinsic: " + extrinsicState);
}
}
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);
}
}
12. 代理模式 (Proxy)
目的:为其他对象提供一种代理以控制对这个对象的访问。
java
public interface Subject {
void request();
}
public class RealSubject implements Subject {
public void request() {
System.out.println("RealSubject request");
}
}
public class Proxy implements Subject {
private RealSubject realSubject;
public void request() {
if (realSubject == null) {
realSubject = new RealSubject();
}
realSubject.request();
}
}
三、行为型模式 (11种)
13. 责任链模式 (Chain of Responsibility)
目的:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。
java
public abstract class Handler {
protected Handler successor;
public void setSuccessor(Handler successor) {
this.successor = successor;
}
public abstract void handleRequest(Request request);
}
public class ConcreteHandler extends Handler {
public void handleRequest(Request request) {
if (canHandle(request)) {
// 处理请求
} else if (successor != null) {
successor.handleRequest(request);
}
}
}
14. 命令模式 (Command)
目的:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化。
java
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 Invoker {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void executeCommand() {
command.execute();
}
}
15. 解释器模式 (Interpreter)
目的:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
java
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);
}
}
16. 迭代器模式 (Iterator)
目的:提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
java
public interface Iterator {
boolean hasNext();
Object next();
}
public class ConcreteIterator implements Iterator {
private List<Object> list;
private int index = 0;
public ConcreteIterator(List<Object> list) {
this.list = list;
}
public boolean hasNext() {
return index < list.size();
}
public Object next() {
return list.get(index++);
}
}
17. 中介者模式 (Mediator)
目的:用一个中介对象来封装一系列的对象交互。
java
public interface Mediator {
void notify(Colleague sender, String event);
}
public class ConcreteMediator implements Mediator {
private Colleague colleague1;
private Colleague colleague2;
public void setColleague1(Colleague colleague1) {
this.colleague1 = colleague1;
}
public void notify(Colleague sender, String event) {
if (sender == colleague1) {
colleague2.receive(event);
} else {
colleague1.receive(event);
}
}
}
18. 备忘录模式 (Memento)
目的:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。
java
public class Originator {
private String state;
public Memento createMemento() {
return new Memento(state);
}
public void restoreMemento(Memento memento) {
this.state = memento.getState();
}
}
public class Memento {
private final String state;
public Memento(String state) {
this.state = state;
}
public String getState() {
return state;
}
}
19. 观察者模式 (Observer)
目的:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
java
public interface Observer {
void update();
}
public class ConcreteObserver implements Observer {
public void update() {
System.out.println("Observer notified");
}
}
public class Subject {
private List<Observer> observers = new ArrayList<>();
public void attach(Observer observer) {
observers.add(observer);
}
public void notifyObservers() {
for (Observer observer : observers) {
observer.update();
}
}
}
20. 状态模式 (State)
目的:允许一个对象在其内部状态改变时改变它的行为。
java
public interface State {
void handle();
}
public class Context {
private State state;
public void setState(State state) {
this.state = state;
}
public void request() {
state.handle();
}
}
21. 策略模式 (Strategy)
目的:定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。
java
public interface Strategy {
void algorithm();
}
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.algorithm();
}
}
22. 模板方法模式 (Template Method)
目的:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。
java
public abstract class AbstractClass {
public void templateMethod() {
primitiveOperation1();
primitiveOperation2();
}
protected abstract void primitiveOperation1();
protected abstract void primitiveOperation2();
}
23. 访问者模式 (Visitor)
目的:表示一个作用于某对象结构中的各元素的操作,它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
java
public interface Visitor {
void visit(ElementA elementA);
void visit(ElementB elementB);
}
public interface Element {
void accept(Visitor visitor);
}
public class ElementA implements Element {
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
总结
设计模式是解决特定问题的经验总结,合理使用可以:
- 提高代码复用性
- 增强系统可维护性
- 提高开发效率
- 使代码更易于理解
但也要避免过度设计,应根据实际需求选择合适的模式。理解每种模式的适用场景比记住代码实现更重要。
猜你喜欢
- 2025-07-28 彻底搞懂Spring依赖注入(一)Bean实例创建过程
- 2025-07-28 一文深入了解23种设计模式与六大原则的细枝末节 内含视频和文档
- 2025-07-28 快速上手Java设计模式之简介(java中的设计模式及使用场景)
- 2025-07-28 《深入理解javascript原型和闭包系列》 知识点整理
- 2025-07-28 5 分钟搭建 Node.js 微服务原型(node.js创建服务)
- 2025-07-28 JYM 设计模式系列- 责任链模式,装饰模式,让你的代码更优雅!
- 2025-07-28 一文搞懂JavaScript原型及原型链(附代码)
- 2025-07-28 JavaScript 原型链、prototype、__proto__详解
- 2025-07-28 Java设计模式面试题及答案整理(2025最新版)
- 2025-07-28 Java 面试题:Spring 配置 Bean 实例化有哪些方式?
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- java反编译工具 (77)
- java反射 (57)
- java接口 (61)
- java随机数 (63)
- java7下载 (59)
- java数据结构 (61)
- java 三目运算符 (65)
- java对象转map (63)
- Java继承 (69)
- java字符串替换 (60)
- 快速排序java (59)
- java并发编程 (58)
- java api文档 (60)
- centos安装java (57)
- java调用webservice接口 (61)
- java深拷贝 (61)
- 工厂模式java (59)
- java代理模式 (59)
- java.lang (57)
- java连接mysql数据库 (67)
- java重载 (68)
- java 循环语句 (66)
- java反序列化 (58)
- java时间函数 (60)
- java是值传递还是引用传递 (62)
本文暂时没有评论,来添加一个吧(●'◡'●)