杰瑞科技汇

Java中pattern指什么?如何使用?

Of course! In Java, the term "pattern" can refer to several different concepts. I'll cover the three most common ones:

Java中pattern指什么?如何使用?-图1
(图片来源网络,侵删)
  1. Design Patterns: Reusable, high-level solutions to common software design problems.
  2. Regular Expressions (Regex): A sequence of characters for defining a search pattern in text.
  3. Number/Star Patterns: A classic programming exercise where you print shapes using loops and characters.

Let's break down each one with clear explanations and code examples.


Design Patterns

Design patterns are best practices, reusable solutions to common problems that software developers face while designing applications. They represent the proven approaches to solving recurring problems. The "Gang of Four" (GoF) book is the canonical reference, which catalogs 23 classic patterns.

They are categorized into three groups:

A. Creational Patterns

These patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation.

Java中pattern指什么?如何使用?-图2
(图片来源网络,侵删)
  • Singleton: Ensures a class has only one instance and provides a global point to access it.

    • Use Case: Database connection pools, logging services, configuration managers.

    • Example:

      public class Singleton {
      // Private static instance of the class
      private static Singleton instance;
      // Private constructor to prevent instantiation from outside
      private Singleton() {}
      // Public static method to get the instance
      public static Singleton getInstance() {
          if (instance == null) {
              instance = new Singleton();
          }
          return instance;
      }
      }
  • Factory Method: Defines an interface for creating an object but lets subclasses decide which class to instantiate.

    Java中pattern指什么?如何使用?-图3
    (图片来源网络,侵删)
    • Use Case: When you want your code to be independent of how its objects are created, composed, and represented.
    • Example:
      // Product interface
      interface Shape {
      void draw();
      }

    // Concrete Products class Circle implements Shape { public void draw() { System.out.println("Drawing a Circle"); } } class Square implements Shape { public void draw() { System.out.println("Drawing a Square"); } }

    // Factory 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; } }

B. Structural Patterns

These patterns explain how to assemble objects and classes into larger structures while keeping these structures flexible and efficient.

  • Adapter: Allows the interface of an existing class to be used as another interface. It acts as a bridge between two incompatible interfaces.

    • Use Case: Integrating a new library with an existing system, or using multiple third-party libraries with different but similar interfaces.
    • Example:
      // The existing class with a different interface
      class LegacyRectangle {
      public void draw(int x1, int y1, int x2, int y2) {
          System.out.println("Drawing a rectangle from (" + x1 + "," + y1 + ") to (" + x2 + "," + y2 + ")");
      }
      }

    // The target interface the client expects interface Shape { void draw(int x, int y, int width, int height); }

    // The Adapter class class RectangleAdapter implements Shape { private LegacyRectangle legacyRectangle;

    public RectangleAdapter(LegacyRectangle legacyRectangle) {
        this.legacyRectangle = legacyRectangle;
    }
    @Override
    public void draw(int x, int y, int width, int height) {
        legacyRectangle.draw(x, y, x + width, y + height);
    }

C. Behavioral Patterns

These patterns are concerned with algorithms and the assignment of responsibilities between objects.

  • Observer: Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

    • Use Case: Implementing event handling systems, GUI updates, or the Model-View-Controller (MVC) architecture.
    • Example:
      import java.util.ArrayList;
      import java.util.List;

    // Subject (Observable) class Subject { private List observers = new ArrayList<>(); private int state;

    public void attach(Observer observer) {
        observers.add(observer);
    }
    public void setState(int state) {
        this.state = state;
        notifyAllObservers();
    }
    private void notifyAllObservers() {
        for (Observer observer : observers) {
            observer.update(state);
        }
    }

    // Observer interface Observer { void update(int state); }

    // Concrete Observer class BinaryObserver implements Observer { public BinaryObserver(Subject subject) { subject.attach(this); }

    @Override
    public void update(int state) {
        System.out.println("Binary String: " + Integer.toBinaryString(state));
    }

Regular Expressions (Regex)

Regular expressions are sequences of characters that define a search pattern. Java's java.util.regex package provides classes for pattern matching.

  • Key Classes:

    • Pattern: A compiled representation of a regular expression.
    • Matcher: An engine that performs match operations on a character sequence.
    • PatternSyntaxException: An unchecked exception thrown to indicate a syntax error in a regular expression pattern.
  • Common Metacharacters:

    • : Any character
    • ^ : Start of the string
    • : End of the string
    • : Zero or more of the preceding element
    • : One or more of the preceding element
    • : Zero or one of the preceding element
    • {n} : Exactly n times
    • {n,} : n or more times
    • {n,m} : Between n and m times
    • [] : Character class (e.g., [a-z] for any lowercase letter)
    • \d : Any digit (equivalent to [0-9])
    • \w : Any "word" character (alphanumeric + _)
    • \s : Any whitespace character
  • Example:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

public class RegexExample { public static void main(String[] args) { String text = "The email is user@example.com and another one is support@my-site.org."; String regex = "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b";

    // 1. Compile the regex pattern
    Pattern pattern = Pattern.compile(regex);
    // 2. Create a matcher to find the pattern in the text
    Matcher matcher = pattern.matcher(text);
    // 3. Find and print all matches
    System.out.println("Found email addresses:");
    while (matcher.find()) {
        System.out.println(matcher.group());
    }
}

} // Output: // Found email addresses: // user@example.com // support@my-site.org


---
### 3. Number/Star Patterns
This is a common coding challenge for beginners to practice loops and conditional logic. The idea is to print specific shapes to the console.
#### Example: Printing a Pyramid of Stars
This pattern demonstrates nested loops. The outer loop handles the rows, and the inner loops handle the spaces and stars for each row.
```java
public class StarPattern {
    public static void main(String[] args) {
        int rows = 5;
        for (int i = 1; i <= rows; i++) {
            // Loop to print spaces
            for (int j = 1; j <= rows - i; j++) {
                System.out.print(" ");
            }
            // Loop to print stars
            for (int k = 1; k <= 2 * i - 1; k++) {
                System.out.print("*");
            }
            // Move to the next line
            System.out.println();
        }
    }
}

Output:

Example: Printing a Floyd's Triangle

This pattern uses a single number that increments with each step.

public class NumberPattern {
    public static void main(String[] args) {
        int rows = 4;
        int num = 1;
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(num + " ");
                num++;
            }
            System.out.println();
        }
    }
}

Output:

1 
2 3 
4 5 6 
7 8 9 10 

Summary

Type of Pattern Purpose Key Java Concepts
Design Patterns Reusable, high-level solutions for software design problems. Classes, Interfaces, Inheritance, Encapsulation, Singleton, Factory, Observer.
Regular Expressions Defining search patterns in text. java.util.regex package (Pattern, Matcher), Metacharacters (\d, , , etc.).
Number/Star Patterns A programming exercise to practice loops and logic. for loops, while loops, System.out.print, nested loops.
分享:
扫描分享到社交APP
上一篇
下一篇