21xrx.com
2024-09-20 09:04:10 Friday
登录
文章检索 我的文章 写文章
Java设计模式详解——深入剖析23种设计模式及其应用案例
2023-06-15 20:54:33 深夜i     --     --
工厂方法模式 创建型模式 工厂接口

设计模式是面向对象编程中的重要组成部分,Java作为一门面向对象的编程语言,也广泛应用了各种设计模式。本文将深入剖析23种Java设计模式及其应用案例,包括创建型模式、结构型模式和行为型模式。

1. 创建型模式

1.1 工厂方法模式

工厂方法模式是一种常用的创建型模式,用于解决对象的创建问题。通过定义一个工厂接口和多个实现该接口的工厂类,每个工厂类负责创建一种产品,从而使用户可以通过工厂类创建不同的产品对象。

示例代码:


public interface ShapeFactory {

  Shape createShape();

}

public class CircleFactory implements ShapeFactory {

  public Shape createShape() {

    return new Circle();

  }

}

public class RectangleFactory implements ShapeFactory {

  public Shape createShape() {

    return new Rectangle();

  }

}

public interface Shape {

  void draw();

}

public class Circle implements Shape {

  public void draw() {

    System.out.println("画一个圆形");

  }

}

public class Rectangle implements Shape {

  public void draw() {

    System.out.println("画一个矩形");

  }

}

public class Client {

  public static void main(String[] args) {

    ShapeFactory factory = new CircleFactory();

    Shape shape = factory.createShape();

    shape.draw();

    factory = new RectangleFactory();

    shape = factory.createShape();

    shape.draw();

  }

}

1.2 抽象工厂模式

抽象工厂模式是基于工厂方法模式的一种更高级的创建型模式,用于解决产品族的创建问题。通过定义一个抽象工厂接口和多个实现该接口的工厂类,每个工厂类负责创建一组产品,从而使用户可以通过工厂类创建一组相关的产品对象。

示例代码:


public interface ShapeFactory {

  Shape createShape();

}

public class BlueShapeFactory implements ShapeFactory {

  public Shape createShape() {

    return new BlueCircle();

  }

}

public class RedShapeFactory implements ShapeFactory {

  public Shape createShape() {

    return new RedCircle();

  }

}

public interface Shape {

  void draw();

}

public abstract class AbstractCircle implements Shape {

  protected String color;

  public AbstractCircle(String color)

    this.color = color;

  

}

public class BlueCircle extends AbstractCircle {

  public BlueCircle() {

    super("蓝色");

  }

  public void draw() {

    System.out.println("画一个" + color + "的圆形");

  }

}

public class RedCircle extends AbstractCircle {

  public RedCircle() {

    super("红色");

  }

  public void draw() {

    System.out.println("画一个" + color + "的圆形");

  }

}

public class Client {

  public static void main(String[] args) {

    ShapeFactory factory = new BlueShapeFactory();

    Shape shape = factory.createShape();

    shape.draw();

    factory = new RedShapeFactory();

    shape = factory.createShape();

    shape.draw();

  }

}

关键词:抽象工厂模式、创建型模式、产品族

2. 结构型模式

2.1 适配器模式

适配器模式是一种常用的结构型模式,用于解决接口之间的兼容问题。通过定义一个适配器类,该类实现目标接口并包装一个待适配的对象,将不兼容的接口转换为兼容的接口,从而使得原本由于接口不兼容而不能互相调用的类能够协同工作。

示例代码:


public interface Shape {

  void show();

}

public class Rectangle {

  public void display() {

    System.out.println("显示一个矩形");

  }

}

public class RectangleAdapter implements Shape {

  private Rectangle rectangle;

  public RectangleAdapter(Rectangle rectangle)

    this.rectangle = rectangle;

  

  public void show() {

    rectangle.display();

  }

}

public class Client {

  public static void main(String[] args) {

    Shape shape = new RectangleAdapter(new Rectangle());

    shape.show();

  }

}

关键词:适配器模式、结构型模式、适配器类

2.2 装饰器模式

装饰器模式是一种常用的结构型模式,用于动态地给对象添加额外的功能。通过定义一个装饰类,该类实现目标接口并持有一个待装饰的对象,从而实现对目标对象的透明装饰,同时又不改变原对象的接口和实现。

示例代码:


public interface Shape {

  void draw();

}

public class Circle implements Shape {

  public void draw() {

    System.out.println("画一个圆形");

  }

}

public abstract class ShapeDecorator implements Shape {

  protected Shape shape;

  public ShapeDecorator(Shape shape)

    this.shape = shape;

  

  public void draw() {

    shape.draw();

  }

}

public class RedShapeDecorator extends ShapeDecorator {

  public RedShapeDecorator(Shape shape) {

    super(shape);

  }

  public void draw() {

    shape.draw();

    setRedBorder();

  }

  private void setRedBorder() {

    System.out.println("设置红色边框");

  }

}

public class Client {

  public static void main(String[] args) {

    Shape circle = new Circle();

    Shape redCircle = new RedShapeDecorator(new Circle());

    Shape redRectangle = new RedShapeDecorator(new Rectangle());

    System.out.println("普通的圆:");

    circle.draw();

    System.out.println("\n带红色边框的圆:");

    redCircle.draw();

    System.out.println("\n带红色边框的矩形:");

    redRectangle.draw();

  }

}

关键词:装饰器模式、结构型模式、装饰类

3. 行为型模式

3.1 观察者模式

观察者模式是一种常用的行为型模式,用于实现对象间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知并自动更新。

示例代码:


public interface Subject {

  void attach(Observer observer);

  void detach(Observer observer);

  void notifyObservers();

}

public class ConcreteSubject implements Subject {

  private List observerList = new ArrayList<>();

  private int state;

  public int getState()

    return state;

  

  public void setState(int state) {

    this.state = state;

    notifyObservers();

  }

  public void attach(Observer observer) {

    observerList.add(observer);

  }

  public void detach(Observer observer) {

    observerList.remove(observer);

  }

  public void notifyObservers() {

    for (Observer observer : observerList) {

      observer.update();

    }

  }

}

public interface Observer {

  void update();

}

public class ConcreteObserver implements Observer {

  private String name;

  private int state;

  private ConcreteSubject subject;

  public ConcreteObserver(String name, ConcreteSubject subject)

    this.name = name;

    this.subject = subject;

  

  public void update() {

    state = subject.getState();

    System.out.println(name + "观察到状态变化:" + state);

  }

}

public class Client {

  public static void main(String[] args) {

    ConcreteSubject subject = new ConcreteSubject();

    Observer observer1 = new ConcreteObserver("观察者1", subject);

    Observer observer2 = new ConcreteObserver("观察者2", subject);

    Observer observer3 = new ConcreteObserver("观察者3", subject);

    subject.attach(observer1);

    subject.attach(observer2);

    subject.attach(observer3);

    subject.setState(1);

    subject.detach(observer2);

    subject.setState(2);

  }

}

关键词:观察者模式、行为型模式、主题对象

3.2 策略模式

策略模式是一种常用的行为型模式,用于动态地决定算法的实现。通过定义一组算法接口和多个实现该接口的策略类,客户端在调用算法时可以任意切换相应的策略,从而实现对算法的动态配置。

示例代码:


public interface Strategy {

  int calculate(int a, int b);

}

public class AddStrategy implements Strategy {

  public int calculate(int a, int b) {

    return a + b;

  }

}

public class SubtractStrategy implements Strategy {

  public int calculate(int a, int b)

    return a - b;

  

}

public class Context {

  private Strategy strategy;

  public Context(Strategy strategy)

    this.strategy = strategy;

  

  public int executeStrategy(int a, int b) {

    return strategy.calculate(a, b);

  }

}

public class Client {

  public static void main(String[] args) {

    Context context = new Context(new AddStrategy());

    System.out.println(context.executeStrategy(1, 2));

    context = new Context(new SubtractStrategy());

    System.out.println(context.executeStrategy(1, 2));

  }

}

关键词:策略模式、行为型模式、算法接口

  
  

评论区

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