Java 设计模式:5 个常用模式实战(附代码)

设计模式是软件开发中可复用的解决方案,能提高代码的可维护性、扩展性和可读性。在 Java 中,掌握常用设计模式对构建健壮应用至关重要。本文将介绍 5 个最常用的 Java 设计模式,包括模式定义、使用场景和实际代码示例。所有代码基于 Java 标准语法,确保实战性。

1. 单例模式(Singleton)

定义:确保一个类只有一个实例,并提供全局访问点。适用于资源共享场景,如数据库连接池或配置管理器。
使用场景:当系统中需要唯一对象时使用,避免重复创建实例浪费资源。
代码示例

public class Singleton {
    // 私有静态实例
    private static Singleton instance;
    
    // 私有构造器,防止外部实例化
    private Singleton() {}
    
    // 全局访问点
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
    
    // 示例方法
    public void showMessage() {
        System.out.println("Singleton instance created.");
    }
}

// 使用示例
public class Main {
    public static void main(String[] args) {
        Singleton obj1 = Singleton.getInstance();
        Singleton obj2 = Singleton.getInstance();
        obj1.showMessage(); // 输出: Singleton instance created.
        System.out.println(obj1 == obj2); // 输出: true (验证单例)
    }
}

2. 工厂模式(Factory)

定义:定义一个创建对象的接口,由子类决定实例化哪个类。用于解耦对象创建和使用。
使用场景:当需要根据条件动态创建不同对象时,如日志记录器或支付处理器。
代码示例

// 产品接口
interface Shape {
    void draw();
}

// 具体产品类
class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a Circle.");
    }
}

class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a Rectangle.");
    }
}

// 工厂类
class ShapeFactory {
    public Shape getShape(String shapeType) {
        if (shapeType == null) return null;
        if (shapeType.equalsIgnoreCase("CIRCLE")) {
            return new Circle();
        } else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
            return new Rectangle();
        }
        return null;
    }
}

// 使用示例
public class Main {
    public static void main(String[] args) {
        ShapeFactory factory = new ShapeFactory();
        Shape shape1 = factory.getShape("CIRCLE");
        shape1.draw(); // 输出: Drawing a Circle.
        Shape shape2 = factory.getShape("RECTANGLE");
        shape2.draw(); // 输出: Drawing a Rectangle.
    }
}

3. 观察者模式(Observer)

定义:定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖者自动收到通知。
使用场景:事件驱动系统,如用户界面更新或消息订阅。
代码示例

import java.util.ArrayList;
import java.util.List;

// 主题接口
interface Subject {
    void registerObserver(Observer o);
    void notifyObservers();
}

// 具体主题类
class NewsAgency implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private String news;
    
    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }
    
    @Override
    public void notifyObservers() {
        for (Observer o : observers) {
            o.update(news);
        }
    }
    
    public void setNews(String news) {
        this.news = news;
        notifyObservers(); // 状态改变时通知观察者
    }
}

// 观察者接口
interface Observer {
    void update(String news);
}

// 具体观察者类
class NewsChannel implements Observer {
    private String channelName;
    
    public NewsChannel(String name) {
        this.channelName = name;
    }
    
    @Override
    public void update(String news) {
        System.out.println(channelName + " received news: " + news);
    }
}

// 使用示例
public class Main {
    public static void main(String[] args) {
        NewsAgency agency = new NewsAgency();
        Observer channel1 = new NewsChannel("Channel 1");
        Observer channel2 = new NewsChannel("Channel 2");
        
        agency.registerObserver(channel1);
        agency.registerObserver(channel2);
        
        agency.setNews("Breaking: Java Design Patterns!"); 
        // 输出: Channel 1 received news: Breaking: Java Design Patterns!
        //       Channel 2 received news: Breaking: Java Design Patterns!
    }
}

4. 策略模式(Strategy)

定义:定义一系列算法,封装每个算法,并使它们可互换。让算法独立于使用它的客户端。
使用场景:当需要动态切换行为时,如排序算法或支付方式。
代码示例

// 策略接口
interface PaymentStrategy {
    void pay(int amount);
}

// 具体策略类
class CreditCardPayment implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("Paid " + amount + " via Credit Card.");
    }
}

class PayPalPayment implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("Paid " + amount + " via PayPal.");
    }
}

// 上下文类
class ShoppingCart {
    private PaymentStrategy paymentStrategy;
    
    public void setPaymentStrategy(PaymentStrategy strategy) {
        this.paymentStrategy = strategy;
    }
    
    public void checkout(int amount) {
        paymentStrategy.pay(amount);
    }
}

// 使用示例
public class Main {
    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();
        cart.setPaymentStrategy(new CreditCardPayment());
        cart.checkout(100); // 输出: Paid 100 via Credit Card.
        
        cart.setPaymentStrategy(new PayPalPayment());
        cart.checkout(200); // 输出: Paid 200 via PayPal.
    }
}

5. 装饰器模式(Decorator)

定义:动态地给对象添加额外职责,提供比继承更灵活的替代方案。
使用场景:扩展对象功能而不修改其结构,如 I/O 流处理或 UI 组件增强。
代码示例

// 组件接口
interface Coffee {
    double getCost();
    String getDescription();
}

// 具体组件类
class SimpleCoffee implements Coffee {
    @Override
    public double getCost() {
        return 5.0;
    }
    
    @Override
    public String getDescription() {
        return "Simple Coffee";
    }
}

// 装饰器抽象类
abstract class CoffeeDecorator implements Coffee {
    protected Coffee decoratedCoffee;
    
    public CoffeeDecorator(Coffee coffee) {
        this.decoratedCoffee = coffee;
    }
    
    @Override
    public double getCost() {
        return decoratedCoffee.getCost();
    }
    
    @Override
    public String getDescription() {
        return decoratedCoffee.getDescription();
    }
}

// 具体装饰器类
class MilkDecorator extends CoffeeDecorator {
    public MilkDecorator(Coffee coffee) {
        super(coffee);
    }
    
    @Override
    public double getCost() {
        return super.getCost() + 2.0;
    }
    
    @Override
    public String getDescription() {
        return super.getDescription() + ", with Milk";
    }
}

class SugarDecorator extends CoffeeDecorator {
    public SugarDecorator(Coffee coffee) {
        super(coffee);
    }
    
    @Override
    public double getCost() {
        return super.getCost() + 1.0;
    }
    
    @Override
    public String getDescription() {
        return super.getDescription() + ", with Sugar";
    }
}

// 使用示例
public class Main {
    public static void main(String[] args) {
        Coffee coffee = new SimpleCoffee();
        System.out.println(coffee.getDescription() + " Cost: $" + coffee.getCost()); 
        // 输出: Simple Coffee Cost: $5.0
        
        Coffee milkCoffee = new MilkDecorator(coffee);
        System.out.println(milkCoffee.getDescription() + " Cost: $" + milkCoffee.getCost()); 
        // 输出: Simple Coffee, with Milk Cost: $7.0
        
        Coffee sugarMilkCoffee = new SugarDecorator(milkCoffee);
        System.out.println(sugarMilkCoffee.getDescription() + " Cost: $" + sugarMilkCoffee.getCost()); 
        // 输出: Simple Coffee, with Milk, with Sugar Cost: $8.0
    }
}

总结

这 5 个设计模式(单例、工厂、观察者、策略、装饰器)是 Java 开发中的核心工具,能显著提升代码质量。通过实际代码示例,您可以轻松上手实践。建议在项目中逐步应用这些模式,以积累经验。如果您有特定场景需求,欢迎进一步提问!

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐