Java 常用设计模式详解

设计模式是在软件设计中为解决特定问题而建议的一套通用的解决方案。它们是从经验中总结出来的,并为软件开发者提供了一种解决常见问题的标准方法。Java语言作为一种广泛应用于企业级应用和大型系统开发的编程语言,也广泛地运用了各种设计模式。

创建型模式

1. 单例模式(Singleton Pattern)

单例模式确保类只有一个实例,并提供一个全局访问点。这对于控制资源的共享和限制对象的数量非常有用。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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

2. 工厂模式(Factory Pattern)

工厂模式用于创建对象,而不是在代码中直接使用new关键字。它提供了一个接口来创建对象,但允许子类改变实例化的类型。

interface Shape {
    void draw();
}

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

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

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

3. 抽象工厂模式(Abstract Factory Pattern)

抽象工厂模式提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定它们的类。

interface Color {
    void fill();
}

interface Shape {
    void draw();
}

class Red implements Color {
    public void fill() {
        System.out.println("Inside Red::fill() method.");
    }
}

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

interface AbstractFactory {
    Color getColor(String color);
    Shape getShape(String shape);
}

class ShapeFactory implements AbstractFactory {
    public Shape getShape(String shapeType) {
        if (shapeType.equalsIgnoreCase("RECTANGLE")) {
            return new Rectangle();
        }
        return null;
    }

    public Color getColor(String color) {
        return null;
    }
}

class ColorFactory implements AbstractFactory {
    public Shape getShape(String shapeType) {
        return null;
    }

    public Color getColor(String color) {
        if (color.equalsIgnoreCase("RED")) {
            return new Red();
        }
        return null;
    }
}

4. 建造者模式(Builder Pattern)

建造者模式用于构建一个复杂对象,将其构建过程和表示分离,使得同样的构建过程可以创建不同的表示。

class Meal {
    private String drink;
    private String mainCourse;
    private String side;

    // getters and setters
}

interface MealBuilder {
    void buildDrink();

    void buildMainCourse();

    void buildSide();

    Meal getMeal();
}

class ItalianMealBuilder implements MealBuilder {
    private Meal meal = new Meal();

    public void buildDrink() {
        meal.setDrink("Red Wine");
    }

    public void buildMainCourse() {
        meal.setMainCourse("Pizza");
    }

    public void buildSide() {
        meal.setSide("Bread");
    }

    public Meal getMeal() {
        return meal;
    }
}

class Director {
    private MealBuilder mealBuilder;

    public void setMealBuilder(MealBuilder mealBuilder) {
        this.mealBuilder = mealBuilder;
    }

    public Meal constructMeal() {
        mealBuilder.buildDrink();
        mealBuilder.buildMainCourse();
        mealBuilder.buildSide();
        return mealBuilder.getMeal();
    }
}

5. 原型模式(Prototype Pattern)

原型模式通过复制现有对象来创建新对象,而不是通过实例化来创建。

public class Shape implements Cloneable {
    private String id;
    protected String type;

    public String getType() {
        return type;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Object clone() {
        Object clone = null;
        try {
            clone = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }
}

结构型模式

1. 适配器模式(Adapter Pattern)

适配器模式用于将一个类的接口转换成客户端希望的另一个接口。

interface Target {
    void request();
}

class Adaptee {
    public void specificRequest() {
        System.out.println("Specific request");
    }
}

class Adapter implements Target {
    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    public void request() {
        adaptee.specificRequest();
    }
}

2. 桥接模式(Bridge Pattern)

桥接模式用于将抽象部分与它的实现部分分离,以便它们可以独立变化。

interface DrawAPI {
    void drawCircle(int radius, int x, int y);
}

class RedCircle implements DrawAPI {
    public void drawCircle(int radius, int x, int y) {
        System.out.println("Drawing Circle[ color: red, radius: " + radius + ", x: " + x + ", y: " + y + "]");
    }
}

abstract class Shape {
    protected DrawAPI drawAPI;

    protected Shape(DrawAPI drawAPI) {
        this.drawAPI = drawAPI;
    }

    public abstract void draw();
}

class Circle extends Shape {
    private int radius;
    private int x;
    private int y;

    public Circle(int radius, int x, int y, DrawAPI drawAPI) {
        super(drawAPI);
        this.radius = radius;
        this.x = x;
        this.y = y;
    }

    public void draw() {
        drawAPI.drawCircle(radius, x, y);
    }
}

3. 组合模式(Composite Pattern)

组合模式允许客户端统一对待单个对象和对象的组合,将对象组合成树形结构以表示部分-整体的层次结构。

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

interface Component {
    void operation();
}

class Leaf implements Component {
    public void operation() {
        System.out.println("Leaf operation");
    }
}

class Composite implements Component {
    private List<Component> children = new ArrayList<>();

    public void add(Component component) {
        children.add(component);
    }

    public void remove(Component component) {
        children.remove(component);
    }

    public void operation() {
        System.out.println("Composite operation");
        for (Component component : children) {
            component.operation();
        }
    }
}

4. 装饰器模式(Decorator Pattern)

装饰器模式允许通过将对象封装在装饰器类的对象中来动态地添加新功能。

interface Component {
    void operation();
}

class ConcreteComponent implements Component {
    public void operation() {
        System.out.println("ConcreteComponent operation");
    }
}

class Decorator implements Component {
    protected Component component;

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

    public void operation() {
        component.operation();
    }
}

class ConcreteDecoratorA extends Decorator {
    public ConcreteDecoratorA(Component component) {
        super(component);
    }

    public void operation() {
        super.operation();
        System.out.println("ConcreteDecoratorA operation");
    }
}

5. 外观模式(Facade Pattern)

外观模式提供了一个简化的接口,用于访问一个系统的子系统。

class SubSystemA {
    public void operationA() {
        System.out.println("SubSystemA operation");
    }
}

class SubSystemB {
    public void operationB() {
        System.out.println("SubSystemB operation");
    }
}

class SubSystemC {
    public void operationC() {
        System.out.println("SubSystemC operation");
    }
}

class Facade {
    private SubSystemA subSystemA;
    private SubSystemB subSystemB;
    private SubSystemC subSystemC;

    public Facade() {
        this.subSystemA = new SubSystemA();
        this.subSystemB = new SubSystemB();
        this.subSystemC = new SubSystemC();
    }

    public void operation() {
        subSystemA.operationA();
        subSystemB.operationB();
        subSystemC.operationC();
    }
}

行为型模式

1. 策略模式(Strategy Pattern)

策略模式定义了算法家族,分别封装起来,使它们之间可以互相替换,让算法的变化独立于使用算法的客户。

interface Strategy {
    void execute();
}

class ConcreteStrategyA implements Strategy {
    public void execute() {
        System.out.println("ConcreteStrategyA execute");
    }
}

class ConcreteStrategyB implements Strategy {
    public void execute() {
        System.out.println("ConcreteStrategyB execute");
    }
}

class Context {
    private Strategy strategy;

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

    public void executeStrategy() {
        strategy.execute();
    }
}

2. 观察者模式(Observer Pattern)

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

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

interface Observer {
    void update(String message);
}

class ConcreteObserver implements Observer {
    private String name;

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

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

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

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

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

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

3. 命令模式(Command Pattern)

命令模式将请求封装成对象,使得可以参数化客户端对象,队列化请求,或者对请求进行操作。

interface Command {
    void execute();
}

class ConcreteCommand implements Command {
    private Receiver receiver;

    public ConcreteCommand(Receiver receiver) {
        this.receiver = receiver;
    }

    public void execute() {
        receiver.action();
    }
}

class Receiver {
    public void action() {
        System.out.println("Receiver action");
    }
}

class Invoker {
    private Command command;

    public void setCommand(Command command) {
        this.command = command;
    }

    public void executeCommand() {
        command.execute();
    }
}

4. 状态模式(State Pattern)

状态模式允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类。

interface State {
    void handle();
}

class ConcreteStateA implements State {
    public void handle() {
        System.out.println("ConcreteStateA handle");
    }
}

class ConcreteStateB implements State {
    public void handle() {
        System.out.println("ConcreteStateB handle");
    }
}

class Context {
    private State state;

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

    public void request() {
        state.handle();
    }
}

5. 责任链模式(Chain of Responsibility Pattern)

责任链模式通过为多个对象提供处理请求的机会,将这些对象连接起来,从而解耦发送者和接收者。

abstract class Handler {
    protected Handler successor;

    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }

    public abstract void handleRequest(int request);
}

class ConcreteHandlerA extends Handler {
    public void handleRequest(int request) {
        if (request < 10) {
            System.out.println("ConcreteHandlerA handles request: " + request);
        } else if (successor != null) {
            successor.handleRequest(request);
        }
    }
}

class ConcreteHandlerB extends Handler {
    public void handleRequest(int request) {
        if (request >= 10 && request < 20) {
            System.out.println("ConcreteHandlerB handles request: " + request);
        } else if (successor != null) {
            successor.handleRequest(request);
        }
    }
}

以上介绍了Java中常用的一些设计模式,包括创建型模式、结构型模式和行为型模式。设计模式是在软件工程中为了解决特定问题而形成的一套通用解决方案,通过使用这些设计模式,可以提高代码的可维护性、可扩展性和重用性。

在实际开发中,选择适当的设计模式是非常重要的,因为它能够使得系统更加灵活、易于扩展,并且更容易维护。不同的设计模式适用于不同的场景,根据具体的问题和需求选择合适的设计模式是关键。

通过创建型模式,我们可以更灵活地创建对象,管理对象的生命周期;通过结构型模式,我们可以更好地组织类和对象,实现系统的解耦;而通过行为型模式,我们可以更好地组织对象之间的通信和协作,使系统更加灵活和可维护。

设计模式不是一成不变的定式,而是根据具体情况来选择和使用的。在实际应用中,可以根据需求灵活地组合使用不同的设计模式,以达到更好的效果。同时,设计模式并不是解决所有问题的银弹,需要在实际应用中谨慎使用,根据具体情况进行权衡和取舍。

总体而言,了解和熟练运用设计模式是提高软件开发水平的一项重要技能。通过对设计模式的深入理解和实际应用,可以写出更加健壮、可维护和可扩展的代码,提高系统的质量和开发效率。

黑马程序员Java设计模式详解, 23种Java设计模式(图解+框架源码分析+实战)

猜你喜欢

转载自blog.csdn.net/Itmastergo/article/details/135262565