10.2. Code Refactoring and Design Patterns

Code refactoring and design patterns are two important concepts in software engineering that help improve code readability, maintainability, and scalability. In this section, we will briefly introduce the basic methods of code refactoring and some commonly used design patterns.

10.2.1. Code refactoring

Code refactoring is the process of improving the internal structure of the software without changing the external behavior of the software. Here are some common refactoring methods:

  1. Extract Method: Extract a complex piece of code into a new method.
  2. Inline Method: Replace the implementation of a simple method directly where it is called.
  3. Extract Class (Extract Class): Extract part of the functionality of a class into a new class.
  4. Merge Class: Merge the functionality of two classes into one class.
  5. Rename: Choose a more meaningful name for a variable, method, or class.

When refactoring code, be sure to write and run test cases to ensure that the behavior of the code after refactoring is consistent with that before refactoring.

10.2.2. Design Patterns

Design patterns are general solutions to a class of problems that recur in object-oriented software design. Here are some commonly used design patterns:

Singleton

The singleton pattern ensures that there is only one instance of a class and provides a global point of access. The following is an implementation of the singleton pattern:

public class Singleton {
    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        return INSTANCE;
    }
}
Factory Method Pattern (Factory Method)

The factory method pattern defines an interface for creating objects and lets subclasses decide which class to instantiate. The following is an example of the factory method pattern:

public interface Animal {
    void speak();
}

public class Dog implements Animal {
    @Override
    public void speak() {
        System.out.println("Woof!");
    }
}

public class Cat implements Animal {
    @Override
    public void speak() {
        System.out.println("Meow!");
    }
}

public abstract class AnimalFactory {
    public abstract Animal createAnimal();

    public static AnimalFactory createFactory(String type) {
        if ("dog".equalsIgnoreCase(type)) {
            return new DogFactory();
        } else if ("cat".equalsIgnoreCase(type)) {
            return new CatFactory();
        }
        throw new IllegalArgumentException("Invalid type: " + type);
    }
}

public class DogFactory extends AnimalFactory {
    @Override
    public Animal createAnimal() {
        return new Dog();
    }
}

public class CatFactory extends AnimalFactory {
    @Override
    public Animal createAnimal() {
        return new Cat();
    }
}

Code using the factory method pattern:

public class Main {
    public static void main(String[] args) {
        AnimalFactory factory = AnimalFactory.createFactory("dog");
        Animal animal = factory.createAnimal();
        animal.speak(); // 输出 "Woof!"
    }
}
Observer pattern (Observer)

Observer mode defines a one-to-many dependency, allowing multiple observer objects to monitor a subject object at the same time, and notify all observers when the subject object changes.

public interface Observer {
    void update(String message);
}

public class ConcreteObserver implements Observer {
    private String name;

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

    @Override
    public void update(String message) {
        System.out.println(name + " received message: " + message);
    }
}

public interface Subject {
    void registerObserver(Observer observer);

    void unregisterObserver(Observer observer);

    void notifyObservers(String message);
}

public class ConcreteSubject implements Subject {
    private List<Observer> observers = new ArrayList<>();

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void unregisterObserver(Observer observer) {
        observers.remove(observer);
    }

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

Code using the Observer pattern:

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

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

        subject.registerObserver(observer1);
        subject.registerObserver(observer2);

        subject.notifyObservers("Hello, World!"); // 输出 "Observer 1 received message: Hello, World!" 和 "Observer 2 received message: Hello, World!"
    }
}

The above is just a brief introduction to some basic concepts of code refactoring and design patterns. To truly master these knowledge, you need to learn and practice continuously in the actual programming process. If you encounter problems during programming, try to use refactoring and design patterns to improve the structure of the code and improve the quality of the code. Recommended reading:

https://mp.weixin.qq.com/s/dV2JzXfgjDdCmWRmE0glDA

https://mp.weixin.qq.com/s/an83QZOWXHqll3SGPYTL5g

Guess you like

Origin blog.csdn.net/u010671061/article/details/131038747