Java中的设计模式:完整指南与示例
设计模式(design patterns)是软件开发中常见问题的经过验证的解决方案。在Java中,由于该语言严格的面向对象范式,这些模式尤其受欢迎。使用模式可以使代码更加灵活、可维护和可扩展。
在本文中,我们将介绍Java中设计模式的三个主要类别:创建型、结构型和行为型。每种模式都将附带一个实际的代码示例。
创建型模式(Creational Patterns)
创建型模式管理对象的创建过程,使系统独立于对象的构造方式。我们将介绍两种最流行的模式:Singleton和Factory Method。
Singleton(单例)
Singleton确保一个类只有一个实例,并提供一个全局访问点。此模式常用于数据库连接、日志记录或缓存。
Java中线程安全Singleton的实现示例:
public class DatabaseConnection { private static volatile DatabaseConnection instance; private String connectionString;
private DatabaseConnection(String connectionString) { this.connectionString = connectionString; }
public static DatabaseConnection getInstance(String connectionString) { if (instance == null) { synchronized (DatabaseConnection.class) { if (instance == null) { instance = new DatabaseConnection(connectionString); } } } return instance; }
public void connect() { System.out.println("连接到 " + connectionString); }}使用方式:
DatabaseConnection db = DatabaseConnection.getInstance("jdbc:mysql://localhost:3306/mydb");db.connect();Factory Method(工厂方法)
Factory Method定义了一个创建对象的接口,但允许子类更改所创建对象的类型。这可以将实例的创建委托给子类。
用于创建不同类型通知的工厂方法示例:
interface Notification { void send(String message);}
class EmailNotification implements Notification { public void send(String message) { System.out.println("发送email: " + message); }}
class SMSNotification implements Notification { public void send(String message) { System.out.println("发送SMS: " + message); }}
abstract class NotificationFactory { public abstract Notification createNotification();
public void notifyUser(String message) { Notification notification = createNotification(); notification.send(message); }}
class EmailNotificationFactory extends NotificationFactory { public Notification createNotification() { return new EmailNotification(); }}
class SMSNotificationFactory extends NotificationFactory { public Notification createNotification() { return new SMSNotification(); }}使用方式:
NotificationFactory factory = new EmailNotificationFactory();factory.notifyUser("您的订单已确认!");结构型模式(Structural Patterns)
结构型模式描述了如何组合类和对象以形成更大的结构。我们将介绍Adapter(适配器)模式。
Adapter(适配器)
Adapter允许接口不兼容的对象协同工作。它包装一个对象,为客户端提供所需的接口。
用于集成旧日志系统的适配器示例: