Java 常用设计原则和设计模式

73 阅读3分钟

一、设计原则(SOLID 原则)

1. 单一职责原则(Single Responsibility Principle, SRP)

定义:一个类应该只有一个引起其变化的原因,即一个类只负责一个功能。

  • 好处:降低耦合性,增强代码可维护性。
  • 示例
class ReportGenerator {
    public void generateReport() {
        // 负责生成报告的逻辑
    }
}

class ReportPrinter {
    public void printReport() {
        // 负责打印报告的逻辑
    }
}

2. 开闭原则(Open/Closed Principle, OCP)

定义:软件实体(类、模块、函数等)应该对扩展开放,对修改关闭。

  • 好处:在不修改已有代码的基础上扩展新功能,减少风险。
  • 示例
abstract class Shape {
    public abstract void draw();
}

class Circle extends Shape {
    public void draw() {
        System.out.println("Drawing Circle");
    }
}

class Rectangle extends Shape {
    public void draw() {
        System.out.println("Drawing Rectangle");
    }
}

3. 里氏替换原则(Liskov Substitution Principle, LSP)

定义:子类可以扩展父类的功能,但不能改变父类原有功能。

  • 好处:保证程序的正确性和可扩展性。
  • 示例
class Bird {
    public void fly() {
        System.out.println("I can fly");
    }
}

class Sparrow extends Bird { }

4. 接口隔离原则(Interface Segregation Principle, ISP)

定义:接口应该小而专,不应该大而全。

  • 好处:降低类对接口的依赖,提升系统灵活性。
  • 示例
interface Printer {
    void print();
}

interface Scanner {
    void scan();
}

class MultiFunctionPrinter implements Printer, Scanner {
    public void print() {
        System.out.println("Printing...");
    }

    public void scan() {
        System.out.println("Scanning...");
    }
}

5. 依赖倒置原则(Dependency Inversion Principle, DIP)

定义:高层模块不应该依赖于低层模块,二者都应该依赖于抽象。

  • 好处:提高系统的灵活性和可维护性。
  • 示例
interface NotificationService {
    void sendMessage(String message);
}

class EmailService implements NotificationService {
    public void sendMessage(String message) {
        System.out.println("Sending email: " + message);
    }
}

class User {
    private NotificationService notificationService;

    public User(NotificationService notificationService) {
        this.notificationService = notificationService;
    }

    public void notifyUser(String message) {
        notificationService.sendMessage(message);
    }
}

二、常用设计模式

1. 单例模式(Singleton Pattern)

定义:确保一个类只有一个实例,并提供全局访问点。

  • 应用场景:数据库连接池、配置管理器。
  • 示例
class Singleton {
    private static Singleton instance;

    private Singleton() { }

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

2. 工厂模式(Factory Pattern)

定义:创建对象时不指定具体类,由工厂方法决定实例化的类型。

  • 应用场景:创建复杂对象时统一管理。
  • 示例
interface Shape {
    void draw();
}

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

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

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

3. 观察者模式(Observer Pattern)

定义:定义对象间的一对多依赖关系,当一个对象状态发生改变时,通知所有依赖它的对象。

  • 应用场景:事件监听、订阅发布系统。
  • 示例
import java.util.ArrayList;
import java.util.List;

interface Observer {
    void update(String message);
}

class ConcreteObserver implements Observer {
    public void update(String message) {
        System.out.println("收到消息: " + message);
    }
}

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

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

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

4. 策略模式(Strategy Pattern)

定义:定义一系列算法,将每种算法封装起来,并使它们可以互换。

  • 应用场景:支付方式选择、数据排序等。
  • 示例
interface Strategy {
    int execute(int a, int b);
}

class AddStrategy implements Strategy {
    public int execute(int a, int b) {
        return a + b;
    }
}

class MultiplyStrategy implements Strategy {
    public int execute(int a, int b) {
        return a * b;
    }
}

class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public int executeStrategy(int a, int b) {
        return strategy.execute(a, b);
    }
}

5. 装饰器模式(Decorator Pattern)

定义:动态地给对象增加功能,而不影响其他对象。

  • 应用场景:功能扩展,如文件读写的加密和解压。
  • 示例
interface Component {
    void operation();
}

class ConcreteComponent implements Component {
    public void operation() {
        System.out.println("执行基本操作");
    }
}

class Decorator implements Component {
    private Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    public void operation() {
        component.operation();
        System.out.println("扩展的功能");
    }
}

三、总结

  • 设计原则 是写出可维护、可扩展代码的基础。
  • 设计模式 是解决常见问题的最佳实践。

熟练掌握这些设计原则和设计模式,可以帮助你编写更加灵活、易于维护的代码!