侧边栏壁纸
  • 累计撰写 29 篇文章
  • 累计创建 38 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Java 23种设计模式超全详解(一)

16uni
2025-06-11 / 0 评论 / 0 点赞 / 24 阅读 / 0 字 / 正在检测是否收录...
温馨提示:
部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

设计模式是解决软件设计中常见问题的可复用方案,就像建筑领域的"设计蓝图"。

创建型模式(管"生孩子"的)

1. 单例模式(Singleton)

问题:如何保证一个类只有一个实例?
生活案例:一个国家只有一个总统,所有部门都找同一个人办事
核心:私有构造器 + 静态实例 + 全局访问点

public class President {
    private static President instance; // 唯一总统
    
    private President() {} // 禁止外部new总统
    
    public static President getInstance() {
        if (instance == null) {
            instance = new President();
        }
        return instance;
    }
}
// 使用:
President p1 = President.getInstance();
President p2 = President.getInstance();
System.out.println(p1 == p2); // true(同一个人)

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

问题:如何让创建对象更灵活?
生活案例:汽车工厂生产不同车型,客户不关心制造细节
核心:定义创建接口,子类决定实例化哪个类

interface Car {
    void drive();
}

class SUV implements Car {
    public void drive() { System.out.println("越野车行驶"); }
}

class CarFactory {
    public Car createCar(String type) {
        if("SUV".equals(type)) return new SUV();
        return null;
    }
}
// 使用:
Car myCar = new CarFactory().createCar("SUV");
myCar.drive(); // 越野车行驶

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

问题:如何创建相关产品家族?
生活案例:苹果工厂生产iPhone+AirPods,小米工厂生产手机+耳机
核心:工厂接口生产多个关联产品

interface Phone { void call(); }
interface Earphone { void play(); }

// 苹果产品家族
class iPhone implements Phone { /*...*/ }
class AirPods implements Earphone { /*...*/ }

interface TechFactory {
    Phone createPhone();
    Earphone createEarphone();
}

class AppleFactory implements TechFactory {
    public Phone createPhone() { return new iPhone(); }
    public Earphone createEarphone() { return new AirPods(); }
}

4. 建造者模式(Builder)

问题:如何创建复杂对象?
生活案例:点汉堡时定制配料(加芝士/去生菜/多酱料)
核心:分步构建 + 链式调用

class Burger {
    private boolean cheese, lettuce;
    
    static class Builder {
        private boolean cheese = false;
        private boolean lettuce = true;
        
        Builder addCheese() { this.cheese = true; return this; }
        Builder noLettuce() { this.lettuce = false; return this; }
        
        Burger build() {
            Burger burger = new Burger();
            burger.cheese = this.cheese;
            burger.lettuce = this.lettuce;
            return burger;
        }
    }
}
// 使用:
Burger burger = new Burger.Builder()
                    .addCheese()
                    .noLettuce()
                    .build();

5. 原型模式(Prototype)

问题:如何高效创建相似对象?
生活案例:细胞分裂产生相同副本
核心:克隆代替new

class Sheep implements Cloneable {
    String name;
    public Sheep clone() {
        try {
            return (Sheep) super.clone(); // 浅拷贝
        } catch (CloneNotSupportedException e) {
            return null;
        }
    }
}
// 使用:
Sheep dolly = new Sheep();
dolly.name = "多莉";
Sheep clone = dolly.clone();

0

评论区