专业的JAVA编程教程与资源

网站首页 > java教程 正文

Java设计模式实战案例解析(java中设计模式到底是干啥的)

temp10 2025-03-30 21:00:53 java教程 9 ℃ 0 评论

Java设计模式实战案例解析

在软件开发中,设计模式是一种经过验证的方法,用于解决常见的设计问题。它们不仅能够提高代码的复用性、灵活性和可维护性,还能促进团队成员之间的沟通和协作。本文将通过几个具体的实战案例,带你深入了解几种常用的Java设计模式。

目录

  1. 单例模式:确保一个类只有一个实例,并提供一个全局访问点。
  2. 工厂模式:定义创建对象的接口,但让子类决定实例化哪一个类。
  3. 观察者模式:定义对象间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。
  4. 装饰器模式:动态地给一个对象添加一些额外的职责。
  5. 策略模式:定义一系列算法,把每一个算法封装起来,并且使它们可以相互替换。
  6. 总结与反思

1. 单例模式

单例模式的核心思想是确保一个类只有一个实例,并提供一个全局访问点。这在需要频繁创建和销毁的对象时特别有用,比如数据库连接池。

Java设计模式实战案例解析(java中设计模式到底是干啥的)

代码实现

public class Singleton {
    // 私有的静态实例变量
    private static Singleton instance;

    // 私有的构造方法
    private Singleton() {}

    // 公共的静态方法获取实例
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    public void showMessage() {
        System.out.println("Hello, I'm a Singleton!");
    }
}

使用场景

假设我们需要一个全局唯一的配置管理器:

public class ConfigManager {
    public static void main(String[] args) {
        Singleton configManager = Singleton.getInstance();
        configManager.showMessage();
    }
}

小贴士

单例模式的实现需要注意线程安全问题。上面的代码使用了双重检查锁定(Double-Checked Locking)来确保线程安全。


2. 工厂模式

工厂模式用于定义创建对象的接口,但让子类决定实例化哪一个类。工厂方法让一个类的实例化延迟到其子类。

代码实现

// 创建一个接口
interface Shape {
    void draw();
}

// 创建实现类
class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing Circle");
    }
}

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

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

使用场景

假设我们需要根据不同的图形类型绘制不同的形状:

public class FactoryPatternDemo {
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();

        // 获取 Circle 的对象,并调用它的 draw 方法
        Shape shape1 = shapeFactory.getShape("CIRCLE");

        // 调用 Circle 的 draw 方法
        shape1.draw();

        // 获取 Square 的对象,并调用它的 draw 方法
        Shape shape2 = shapeFactory.getShape("SQUARE");

        // 调用 Square 的 draw 方法
        shape2.draw();
    }
}

小贴士

工厂模式使得系统更加灵活,易于扩展新的产品类型,而无需修改现有的代码。


3. 观察者模式

观察者模式定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。

代码实现

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

// 创建 Subject 类
abstract class Subject {
    protected List observers = new ArrayList<>();

    public void attach(Observer observer) {
        observers.add(observer);
    }

    public void detach(Observer observer) {
        observers.remove(observer);
    }

    public abstract void notifyObservers();
}

// 创建 Observer 类
interface Observer {
    void update();
}

// 创建 ConcreteSubject 类
class ConcreteSubject extends Subject {
    private String state;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
        notifyObservers();
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update();
        }
    }
}

// 创建 ConcreteObserver 类
class ConcreteObserver implements Observer {
    private String name;

    public ConcreteObserver(String name) {
        this.name = name;
    }

    @Override
    public void update() {
        System.out.println(name + " received update: State changed to " + ((ConcreteSubject) subject).getState());
    }
}

使用场景

假设我们有一个天气预报系统,需要在状态变化时通知多个客户端:

public class ObserverPatternDemo {
    public static void main(String[] args) {
        ConcreteSubject weatherData = new ConcreteSubject();

        ConcreteObserver observer1 = new ConcreteObserver("Observer 1");
        ConcreteObserver observer2 = new ConcreteObserver("Observer 2");

        weatherData.attach(observer1);
        weatherData.attach(observer2);

        weatherData.setState("Sunny");
        weatherData.setState("Rainy");
    }
}

小贴士

观察者模式非常适合处理事件驱动的应用程序,如GUI应用程序。


4. 装饰器模式

装饰器模式允许动态地给一个对象添加一些额外的职责。它比生成子类更灵活。

代码实现

// 创建 Component 接口
interface Coffee {
    double cost();
}

// 创建 ConcreteComponent 类
class SimpleCoffee implements Coffee {
    @Override
    public double cost() {
        return 10;
    }
}

// 创建 Decorator 类
abstract class CoffeeDecorator implements Coffee {
    protected Coffee decoratedCoffee;

    public CoffeeDecorator(Coffee coffee) {
        this.decoratedCoffee = coffee;
    }

    @Override
    public double cost() {
        return decoratedCoffee.cost();
    }
}

// 创建 ConcreteDecorator 类
class MilkCoffee extends CoffeeDecorator {
    public MilkCoffee(Coffee coffee) {
        super(coffee);
    }

    @Override
    public double cost() {
        return super.cost() + 2;
    }
}

class SugarCoffee extends CoffeeDecorator {
    public SugarCoffee(Coffee coffee) {
        super(coffee);
    }

    @Override
    public double cost() {
        return super.cost() + 1;
    }
}

使用场景

假设我们需要根据客户的口味添加不同的调料:

public class DecoratorPatternDemo {
    public static void main(String[] args) {
        Coffee simpleCoffee = new SimpleCoffee();
        System.out.println("Cost of simple coffee: " + simpleCoffee.cost());

        Coffee milkCoffee = new MilkCoffee(simpleCoffee);
        System.out.println("Cost of milk coffee: " + milkCoffee.cost());

        Coffee sugarMilkCoffee = new SugarCoffee(milkCoffee);
        System.out.println("Cost of sugar milk coffee: " + sugarMilkCoffee.cost());
    }
}

小贴士

装饰器模式可以在不修改原有类的情况下扩展功能,非常适合需要动态添加行为的场景。


5. 策略模式

策略模式定义了一系列算法,并将每一个算法封装起来,使它们可以相互替换。策略模式让算法的变化独立于使用算法的客户。

代码实现

// 创建 Strategy 接口
interface PaymentStrategy {
    void pay(double amount);
}

// 创建 ConcreteStrategy 类
class CreditCardStrategy implements PaymentStrategy {
    @Override
    public void pay(double amount) {
        System.out.println(amount + " paid with credit/debit card");
    }
}

class PayPalStrategy implements PaymentStrategy {
    @Override
    public void pay(double amount) {
        System.out.println(amount + " paid using PayPal.");
    }
}

// 创建 Context 类
class ShoppingCart {
    private List items = new ArrayList<>();
    private PaymentStrategy paymentStrategy;

    public void addItem(Item item) {
        items.add(item);
    }

    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void pay() {
        double totalAmount = calculateTotal();
        paymentStrategy.pay(totalAmount);
    }

    private double calculateTotal() {
        double total = 0;
        for (Item item : items) {
            total += item.getPrice();
        }
        return total;
    }
}

class Item {
    private String name;
    private double price;

    public Item(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public double getPrice() {
        return price;
    }
}

使用场景

假设我们需要支持不同的支付方式:

public class StrategyPatternDemo {
    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();

        cart.addItem(new Item("iPhone", 1000));
        cart.addItem(new Item("iPad", 500));

        cart.setPaymentStrategy(new CreditCardStrategy());
        cart.pay();

        cart.setPaymentStrategy(new PayPalStrategy());
        cart.pay();
    }
}

小贴士

策略模式使得算法可以在运行时动态选择,增强了系统的灵活性。


总结与反思

通过以上几个实战案例,我们可以看到设计模式在解决实际问题时的强大之处。每一种模式都有其适用的场景和优势,合理运用这些模式可以使我们的代码更加简洁、易维护和可扩展。

希望这篇文章能够帮助你在Java编程之路上走得更远,如果你有任何疑问或建议,请随时留言交流!


祝你编程愉快!

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表