Java常用设计模式

        设计模式是软件开发中解决常见问题的模板或指南。Java中的23种设计模式通常被分为三大类:创建型(Creational Patterns)结构型(Structural Patterns)行为型(Behavioral Patterns)


创建型模式


1.单例模式(Singleton Pattern)

        定义:确保一个类只有一个实例,并提供全局访问点。
        用途:全局配置管理、数据库连接池等需要唯一实例的场景。

// 单例模式:确保一个类只有一个实例,并提供全局访问点
public class Singleton {
    // 使用volatile防止指令重排,确保线程安全
    private static volatile Singleton instance;
    
    // 私有构造器防止外部实例化
    private Singleton() {}
    
    // 双重检查锁定(Double-Check Locking)
    public static Singleton getInstance() {
        if (instance == null) { // 第一次检查
            synchronized (Singleton.class) {
                if (instance == null) { // 第二次检查
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

// 调用
public class Main {
    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
    }
}

2.工厂方法模式(Factory Method Pattern)

        定义:定义一个创建对象的接口,但由子类决定实例化哪个类。
        用途:解耦对象的创建与使用(如不同数据库驱动)。

// 产品接口
interface Product {
    void use();
}

// 具体产品
class ConcreteProduct implements Product {
    @Override
    public void use() {
        System.out.println("Using ConcreteProduct");
    }
}

// 抽象工厂(定义工厂方法)
abstract class Factory {
    public abstract Product createProduct();
}

// 具体工厂(实现工厂方法)
class ConcreteFactory extends Factory {
    @Override
    public Product createProduct() {
        return new ConcreteProduct();
    }
}

// 调用
public class Main {
    public static void main(String[] args) {
        Factory factory = new ConcreteFactory();
        Product product = factory.createProduct();
        product.use();
    }
}

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

        定义:提供一个接口,创建一组相关或依赖对象的家族,而不指定具体类。
        用途:跨平台UI组件库(如Windows/Mac风格的按钮、文本框)。

        区别:
                工厂方法:一个子类创建一个产品,子类决定实例化单一产品。
                抽象工厂:一个子类创建多个相关产品,子类实例化一组相关产品。

    // 产品族1接口
    interface Button {
        void click();
    }
    
    // 具体产品1(Windows)
    class WindowsButton implements Button {
        @Override
        public void click() {
            System.out.println("Windows Button clicked");
        }
    }
    
    // 产品族2接口
    interface TextField {
        void type();
    }
    
    // 具体产品2(Windows)
    class WindowsTextField implements TextField {
        @Override
        public void type() {
            System.out.println("Windows TextField typed");
        }
    }
    
    // 抽象工厂接口
    interface GUIFactory {
        Button createButton();
        TextField createTextField();
    }
    
    // 具体工厂(Windows)
    class WindowsFactory implements GUIFactory {
        @Override
        public Button createButton() {
            return new WindowsButton();
        }
    
        @Override
        public TextField createTextField() {
            return new WindowsTextField();
        }
    }
    
    // 调用
    public class Main {
        public static void main(String[] args) {
            GUIFactory factory = new WindowsFactory();
            Button button = factory.createButton();
            TextField textField = factory.createTextField();
            button.click();
            textField.type();
        }
    }

      4.建造者模式(Builder Pattern)

              定义:将复杂对象的构建过程分离,允许逐步构造不同表示形式。
              用途:创建复杂对象(如SQL查询构造器)。

      // 产品类(复杂对象)
      class Car {
          private String engine;
          private String tires;
          
          // 内部Builder类
          static class Builder {
              private String engine;
              private String tires;
              
              public Builder engine(String engine) {
                  this.engine = engine;
                  return this;
              }
              
              public Builder tires(String tires) {
                  this.tires = tires;
                  return this;
              }
              
              public Car build() {
                  return new Car(this);
              }
          }
          
          // 私有构造器,通过Builder创建
          private Car(Builder builder) {
              this.engine = builder.engine;
              this.tires = builder.tires;
          }
      }
      
      // 调用
      public class Main {
          public static void main(String[] args) {
              Car car = new Car.Builder()
                  .engine("V8")
                  .tires("All-Terrain")
                  .build();
          }
      }


      结构型模式


      1.适配器模式(Adapter Pattern)

              定义:将一个类的接口转换成客户端期望的另一个接口。
              用途:兼容旧代码或第三方库(如USB转Type-C适配器)。

      // 旧接口
      interface OldSystem {
          void oldMethod();
      }
      
      // 适配的目标接口
      interface NewSystem {
          void newMethod();
      }
      
      // 适配器:将旧接口适配为新接口
      class Adapter implements NewSystem {
          private OldSystem oldSystem;
          
          public Adapter(OldSystem oldSystem) {
              this.oldSystem = oldSystem;
          }
          
          @Override
          public void newMethod() {
              oldSystem.oldMethod(); // 调用旧方法
          }
      }
      
      // 旧系统实现
      class OldImplementation implements OldSystem {
          @Override
          public void oldMethod() {
              System.out.println("Old method called");
          }
      }
      
      // 调用
      public class Main {
          public static void main(String[] args) {
              OldSystem old = new OldImplementation();
              NewSystem adapter = new Adapter(old);
              adapter.newMethod(); // 通过适配器调用旧方法
          }
      }

      2.装饰者模式(Decorator Pattern)

              定义:动态地为对象添加额外职责,通过包装原始对象实现。
              用途:扩展功能而不修改类(如为咖啡添加牛奶、糖)。

      // 组件接口
      interface Coffee {
          String getDescription();
          double cost();
      }
      
      // 具体组件
      class SimpleCoffee implements Coffee {
          @Override
          public String getDescription() {
              return "Simple Coffee";
          }
          
          @Override
          public double cost() {
              return 2.0;
          }
      }
      
      // 装饰者抽象类
      abstract class CoffeeDecorator implements Coffee {
          protected Coffee decoratedCoffee;
          
          public CoffeeDecorator(Coffee decoratedCoffee) {
              this.decoratedCoffee = decoratedCoffee;
          }
          
          @Override
          public String getDescription() {
              return decoratedCoffee.getDescription();
          }
          
          @Override
          public double cost() {
              return decoratedCoffee.cost();
          }
      }
      
      // 具体装饰者(添加牛奶)
      class MilkDecorator extends CoffeeDecorator {
          public MilkDecorator(Coffee decoratedCoffee) {
              super(decoratedCoffee);
          }
          
          @Override
          public String getDescription() {
              return super.getDescription() + ", Milk";
          }
          
          @Override
          public double cost() {
              return super.cost() + 0.5;
          }
      }
      
      // 调用
      public class Main {
          public static void main(String[] args) {
              Coffee coffee = new SimpleCoffee();
              coffee = new MilkDecorator(coffee);
              System.out.println(coffee.getDescription() + " $" + coffee.cost());
          }
      }

      3.代理模式(Proxy Pattern)

              定义:为其他对象提供一个代理,以控制对这个对象的访问。
              用途:延迟加载、权限控制(如虚拟代理、安全代理)。

      // 主题接口
      interface Subject {
          void request();
      }
      
      // 真实主题
      class RealSubject implements Subject {
          @Override
          public void request() {
              System.out.println("RealSubject handling request");
          }
      }
      
      // 代理
      class Proxy implements Subject {
          private RealSubject realSubject;
          
          @Override
          public void request() {
              if (realSubject == null) {
                  realSubject = new RealSubject();
              }
              // 代理逻辑(如权限检查)
              System.out.println("Proxy: Checking access...");
              realSubject.request();
          }
      }
      
      // 调用
      public class Main {
          public static void main(String[] args) {
              Subject proxy = new Proxy();
              proxy.request();
          }
      }

      行为型模式


      1.观察者模式(Observer Pattern)

              定义:定义对象间的一对多依赖,当一个对象状态改变时,自动通知依赖它的对象。
              用途:事件处理系统(如消息订阅、UI数据更新)。

      // 主题接口
      interface Subject {
          void registerObserver(Observer observer);
          void removeObserver(Observer observer);
          void notifyObservers();
      }
      
      // 观察者接口
      interface Observer {
          void update(String message);
      }
      
      // 具体主题
      class WeatherStation implements Subject {
          private List<Observer> observers = new ArrayList<>();
          private String weatherData;
          
          @Override
          public void registerObserver(Observer observer) {
              observers.add(observer);
          }
          
          @Override
          public void removeObserver(Observer observer) {
              observers.remove(observer);
          }
          
          @Override
          public void notifyObservers() {
              for (Observer observer : observers) {
                  observer.update(weatherData);
              }
          }
          
          public void setWeatherData(String data) {
              this.weatherData = data;
              notifyObservers();
          }
      }
      
      // 具体观察者
      class WeatherDisplay implements Observer {
          @Override
          public void update(String message) {
              System.out.println("WeatherDisplay received: " + message);
          }
      }
      
      // 调用
      public class Main {
          public static void main(String[] args) {
              WeatherStation station = new WeatherStation();
              WeatherDisplay display = new WeatherDisplay();
              station.registerObserver(display);
              station.setWeatherData("Sunny");
          }
      }

      2.策略模式(Strategy Pattern)

              定义:定义一系列算法并封装它们,使可以独立于使用它的功能而变化。
              用途:动态切换行为(如排序算法、支付方式选择)。

      // 策略接口
      interface PaymentStrategy {
          void pay(int amount);
      }
      
      // 具体策略(信用卡支付)
      class CreditCardStrategy implements PaymentStrategy {
          private String cardNumber;
          
          public CreditCardStrategy(String cardNumber) {
              this.cardNumber = cardNumber;
          }
          
          @Override
          public void pay(int amount) {
              System.out.println("Paid " + amount + " using Credit Card");
          }
      }
      
      // 上下文
      class Order {
          private PaymentStrategy strategy;
          
          public void setPaymentStrategy(PaymentStrategy strategy) {
              this.strategy = strategy;
          }
          
          public void placeOrder(int amount) {
              strategy.pay(amount);
          }
      }
      
      // 调用
      public class Main {
          public static void main(String[] args) {
              Order order = new Order();
              order.setPaymentStrategy(new CreditCardStrategy("1234-5678"));
              order.placeOrder(100);
          }
      }

      3.命令模式(Command Pattern)

              定义:将请求封装为对象,以便参数化、队列化或记录请求。
              用途:实现撤销/重做、任务队列(如编辑器操作记录)。

      // 命令接口
      interface Command {
          void execute();
      }
      
      // 接收者(执行实际操作)
      class Light {
          public void turnOn() {
              System.out.println("Light turned ON");
          }
          
          public void turnOff() {
              System.out.println("Light turned OFF");
          }
      }
      
      // 具体命令(开灯)
      class TurnOnCommand implements Command {
          private Light light;
          
          public TurnOnCommand(Light light) {
              this.light = light;
          }
          
          @Override
          public void execute() {
              light.turnOn();
          }
      }
      
      // 调用者(Invoker)
      class RemoteControl {
          private Command command;
          
          public void setCommand(Command command) {
              this.command = command;
          }
          
          public void pressButton() {
              command.execute();
          }
      }
      
      // 调用
      public class Main {
          public static void main(String[] args) {
              Light light = new Light();
              Command command = new TurnOnCommand(light);
              RemoteControl remote = new RemoteControl();
              remote.setCommand(command);
              remote.pressButton();
          }
      }

      评论
      添加红包

      请填写红包祝福语或标题

      红包个数最小为10个

      红包金额最低5元

      当前余额3.43前往充值 >
      需支付:10.00
      成就一亿技术人!
      领取后你会自动成为博主和红包主的粉丝 规则
      hope_wisdom
      发出的红包
      实付
      使用余额支付
      点击重新获取
      扫码支付
      钱包余额 0

      抵扣说明:

      1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
      2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

      余额充值