21xrx.com
2024-09-17 04:12:07 Tuesday
登录
文章检索 我的文章 写文章
Java 设计模式:常用模式总结
2023-06-15 16:31:23 深夜i     --     --
Java 设计模式 工厂模式 单例模式 策略模式

Java 设计模式是指在软件开发过程中对于特定的问题解决方案的一个重现,可用于提高代码的可读性、可复用性、可维护性、可扩展性等。本文将对常用的设计模式进行总结,并介绍各自的应用场景和代码案例。

1. 工厂模式(Factory Pattern)

工厂模式旨在为对象创建提供一种灵活的接口,将对象的创建过程与客户端代码解耦合,使得系统可以在不修改代码的情况下为对象创建提供多种实现方式。例如:

public interface Shape {

  void draw();

}

public class Circle implements Shape {

  @Override

  public void draw() {

    System.out.println("Draw circle.");

  }

}

public class Rectangle implements Shape {

  @Override

  public void draw() {

    System.out.println("Draw rectangle.");

  }

}

public class ShapeFactory {

  public Shape getShape(String name) {

    if (name.equals("Circle")) {

      return new Circle();

    } else if (name.equals("Rectangle")) {

      return new Rectangle();

    }

    return null;

  }

}

2. 单例模式(Singleton Pattern)

单例模式保证在整个应用程序生命周期中只存在一个实例对象,并提供全局访问点供客户端访问,例如:

public class Singleton {

  private static Singleton instance;

  private Singleton() {}

  public static synchronized Singleton getInstance() {

    if (instance == null) {

      instance = new Singleton();

    }

    return instance;

  }

}

3. 策略模式(Strategy Pattern)

策略模式将不同算法的实现分离出来,使得算法的变化不会影响整个系统。客户端可以在运行时动态设置使用的算法,例如:

public interface SortStrategy {

  void sort(int[] arr);

}

public class QuickSortStrategy implements SortStrategy {

  @Override

  public void sort(int[] arr) {

    // Quick Sort Implementation...

  }

}

public class MergeSortStrategy implements SortStrategy {

  @Override

  public void sort(int[] arr) {

    // Merge Sort Implementation...

  }

}

public class SortContext {

  private SortStrategy strategy;

  public SortContext(SortStrategy strategy) {

    this.strategy = strategy;

  }

  public void setStrategy(SortStrategy strategy) {

    this.strategy = strategy;

  }

  public void sort(int[] arr) {

    strategy.sort(arr);

  }

}

本文简要介绍了工厂模式、单例模式和策略模式,包括它们的应用场景和代码案例。在实际的应用中,为了提高代码的可读性和可维护性,我们应该根据具体的需求选择适合的设计模式进行编码。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复