Java中的主要设计模式

Java中的设计模式是一套被广泛认可的解决特定问题的解决方案。它们分为三大类:创建型模式、结构型模式和行为型模式。以下是一些常见的设计模式及其简要介绍和代码实现示例:

创建型模式

  1. 单例模式(Singleton): 确保一个类只有一个实例,并提供一个全局访问点。

    java 复制代码
    public class Singleton {
        private static Singleton instance;
        private Singleton() {}
    
        public static synchronized Singleton getInstance() {
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
    }
  2. 工厂方法模式(Factory Method): 定义一个用于创建对象的接口,让子类决定实例化哪一个类。

    java 复制代码
    interface Product {
        void use();
    }
    
    class ConcreteProduct implements Product {
        public void use() {
            System.out.println("Using ConcreteProduct");
        }
    }
    
    abstract class Creator {
        abstract Product factoryMethod();
    }
    
    class ConcreteCreator extends Creator {
        public Product factoryMethod() {
            return new ConcreteProduct();
        }
    }
  3. 建造者模式(Builder): 用于创建一个复杂对象,同时允许用户只通过指定复杂对象的类型和内容就能构建它们。

    java 复制代码
    class Product {
        private String part1;
        private String part2;
    
        public static class Builder {
            private String part1;
            private String part2;
    
            public Builder setPart1(String part1) {
                this.part1 = part1;
                return this;
            }
    
            public Builder setPart2(String part2) {
                this.part2 = part2;
                return this;
            }
    
            public Product build() {
                return new Product(this.part1, this.part2);
            }
        }
    
        private Product(String part1, String part2) {
            this.part1 = part1;
            this.part2 = part2;
        }
    }

结构型模式

  1. 适配器模式(Adapter): 允许对象间的接口不兼容问题通过一个"适配器"来解决。

    java 复制代码
    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. 装饰器模式(Decorator): 动态地给一个对象添加额外的职责。

    java 复制代码
    interface Component {
        void operate();
    }
    
    class ConcreteComponent implements Component {
        public void operate() {
            System.out.println("ConcreteComponent");
        }
    }
    
    abstract class Decorator implements Component {
        protected Component component;
    
        public Decorator(Component component) {
            this.component = component;
        }
    
        public void operate() {
            component.operate();
        }
    }
    
    class ConcreteDecoratorA extends Decorator {
        public ConcreteDecoratorA(Component component) {
            super(component);
        }
    
        public void operate() {
            super.operate();
            // Add additional behavior
            System.out.println("ConcreteDecoratorA");
        }
    }

行为型模式

  1. 策略模式(Strategy): 定义一系列算法,把它们一个个封装起来,并使它们可互换。

    java 复制代码
    interface Strategy {
        void execute();
    }
    
    class ConcreteStrategyA implements Strategy {
        public void execute() {
            System.out.println("Strategy A");
        }
    }
    
    class Context {
        private Strategy strategy;
    
        public Context(Strategy strategy) {
            this.strategy = strategy;
        }
    
        public void executeStrategy() {
            strategy.execute();
        }
    }
  2. 观察者模式(Observer): 对象间的一对多依赖关系,当一个对象改变状态时,所有依赖于它的对象都会得到通知并自动更新。

    java 复制代码
    interface Observer {
        void update();
    }
    
    class ConcreteObserver implements Observer {
        public void update() {
            System.out.println("Observer updated");
        }
    }
    
    class Subject {
        private List<Observer> observers = new ArrayList<>();
    
        public void attach(Observer observer) {
            observers.add(observer);
        }
    
        public void notifyObservers() {
            for (Observer observer : observers) {
                observer.update();
            }
        }
    }
相关推荐
BeingACoder1 分钟前
【项目实践】公寓租赁项目(九):SpringBoot与Redis整合的快速入门使用
java·spring boot·redis
绝无仅有2 分钟前
某游戏大厂Java面试深度解析:从多线程到JVM调优(二)
后端·面试·github
Sammyyyyy9 分钟前
MySQL 与 PostgreSQL,该怎么选
数据库·mysql·postgresql·开发工具·servbay
绝无仅有10 分钟前
某游戏大厂Java面试指南:Spring、集合与语言特性深度解析 (三)
后端·面试·github
好记忆不如烂笔头abc11 分钟前
oracle rac多私网的问题
数据库·oracle
程序新视界13 分钟前
数据库的分片与分区:有什么区别?
数据库·后端·mysql
IT_陈寒21 分钟前
Java 17 新特性实战:这5个隐藏功能让你的代码效率提升50%
前端·人工智能·后端
程序员爱钓鱼23 分钟前
Python编程实战 - 函数与模块化编程 - 创建自己的模块与包
后端
Javatutouhouduan27 分钟前
我用ChatGPT,给RabbitMQ加了个连接池
java·spring·rabbitmq·消息中间件·后端开发·java程序员·java八股文
程序员爱钓鱼29 分钟前
Python编程实战 - 函数与模块化编程 - Python内置模块(math、os、sys、random等)
后端·python·ipython