Java设计模式:是优雅的套路,还是“面试官的刁难题”?

举报
喵手 发表于 2025/09/24 21:31:19 2025/09/24
【摘要】 开篇语哈喽,各位小伙伴们,你们好呀,我是喵手。运营社区:C站/掘金/腾讯云/阿里云/华为云/51CTO;欢迎大家常来逛逛  今天我要给大家分享一些自己日常学习到的一些知识点,并以文字的形式跟大家一起交流,互相学习,一个人虽可以走的更快,但一群人可以走的更远。  我是一名后端开发爱好者,工作日常接触到最多的就是Java语言啦,所以我都尽量抽业余时间把自己所学到所会的,通过文章的形式进行输出,...

开篇语

哈喽,各位小伙伴们,你们好呀,我是喵手。运营社区:C站/掘金/腾讯云/阿里云/华为云/51CTO;欢迎大家常来逛逛

  今天我要给大家分享一些自己日常学习到的一些知识点,并以文字的形式跟大家一起交流,互相学习,一个人虽可以走的更快,但一群人可以走的更远。

  我是一名后端开发爱好者,工作日常接触到最多的就是Java语言啦,所以我都尽量抽业余时间把自己所学到所会的,通过文章的形式进行输出,希望以这种方式帮助到更多的初学者或者想入门的小伙伴们,同时也能对自己的技术进行沉淀,加以复盘,查缺补漏。

小伙伴们在批阅的过程中,如果觉得文章不错,欢迎点赞、收藏、关注哦。三连即是对作者我写作道路上最好的鼓励与支持!

前言

不得不说,初学设计模式的时候,我的第一感觉就是:这玩意儿是不是用来“为难”我的?明明写个 new 就能解决的事,非得搞个“工厂”;明明直接 if-else 就能分支的事,偏偏要用个“策略”。🙃

但是!当项目变大、需求变复杂的时候,你就会发现:**设计模式不是装逼,而是救命!**它们就像一组武林秘籍,用得好能让你写出优雅、可扩展的代码;用不好,嗯……那就成了“纸上谈兵”。

今天,我们就来撸一遍几个经典的设计模式,用通俗案例 + 代码演示把它们讲明白,顺便看看它们到底是“救命稻草”,还是“花里胡哨”。


1. 单例模式(Singleton)

场景:某些类在系统中只需要一个实例,比如配置类、日志管理器。

public class Singleton {
    private static volatile Singleton instance;

    private Singleton() {} // 私有构造方法

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton(); // 双重检查锁
                }
            }
        }
        return instance;
    }
}

👉 面试官最爱问的:为什么要加 volatile
答:防止指令重排,避免返回一个“半初始化”的对象。


2. 工厂模式 & 抽象工厂模式

工厂模式

场景:对象创建逻辑复杂时,交给工厂去做。

interface Shape {
    void draw();
}

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

class ShapeFactory {
    public static Shape getShape(String type) {
        if ("circle".equalsIgnoreCase(type)) {
            return new Circle();
        }
        throw new IllegalArgumentException("Unknown type");
    }
}

public class DemoFactory {
    public static void main(String[] args) {
        Shape s = ShapeFactory.getShape("circle");
        s.draw(); // Circle
    }
}

抽象工厂模式

场景:需要创建一族相关的对象。

interface Button { void click(); }
interface TextBox { void show(); }

class WinButton implements Button {
    public void click() { System.out.println("Windows Button"); }
}
class MacButton implements Button {
    public void click() { System.out.println("Mac Button"); }
}

interface GUIFactory {
    Button createButton();
}

class WinFactory implements GUIFactory {
    public Button createButton() { return new WinButton(); }
}
class MacFactory implements GUIFactory {
    public Button createButton() { return new MacButton(); }
}

👉 工厂模式解决“对象怎么造”的问题,抽象工厂模式解决“对象族怎么造”的问题。


3. 观察者模式(Observer)

场景:对象间存在“一对多”的依赖关系,比如事件监听。

import java.util.*;

interface Observer {
    void update(String msg);
}

class User implements Observer {
    private String name;
    public User(String name) { this.name = name; }
    public void update(String msg) {
        System.out.println(name + " 收到消息: " + msg);
    }
}

class WechatServer {
    private List<Observer> observers = new ArrayList<>();
    public void addObserver(Observer o) { observers.add(o); }
    public void notifyAll(String msg) {
        for (Observer o : observers) o.update(msg);
    }
}

public class DemoObserver {
    public static void main(String[] args) {
        WechatServer server = new WechatServer();
        server.addObserver(new User("Alice"));
        server.addObserver(new User("Bob"));
        server.notifyAll("新文章上线啦!");
    }
}

👉 观察者模式就像朋友圈:发个状态,所有关注你的人都能收到。


4. 策略模式(Strategy)

场景:有多种算法可以互换,比如不同的支付方式。

interface PaymentStrategy {
    void pay(int amount);
}

class WechatPay implements PaymentStrategy {
    public void pay(int amount) { System.out.println("用微信支付 " + amount); }
}

class Alipay implements PaymentStrategy {
    public void pay(int amount) { System.out.println("用支付宝支付 " + amount); }
}

class PaymentContext {
    private PaymentStrategy strategy;
    public PaymentContext(PaymentStrategy strategy) { this.strategy = strategy; }
    public void execute(int amount) { strategy.pay(amount); }
}

public class DemoStrategy {
    public static void main(String[] args) {
        PaymentContext ctx = new PaymentContext(new WechatPay());
        ctx.execute(100);
    }
}

👉 策略模式就是把 if-else 拆出来,优雅得像“换皮肤”。


5. 命令模式(Command)

场景:解耦请求的发送者和接收者,比如遥控器控制电器。

interface Command {
    void execute();
}

class Light {
    public void on() { System.out.println("开灯"); }
}

class LightOnCommand implements Command {
    private Light light;
    public LightOnCommand(Light light) { this.light = light; }
    public void execute() { light.on(); }
}

class RemoteControl {
    private Command command;
    public void setCommand(Command c) { this.command = c; }
    public void pressButton() { command.execute(); }
}

👉 命令模式其实就是“把请求打包”,以后要执行啥,随便调。


6. 适配器模式(Adapter)

场景:接口不兼容的时候做“中间人”。

interface Target {
    void request();
}

class Adaptee {
    public void specificRequest() { System.out.println("老接口"); }
}

class Adapter implements Target {
    private Adaptee adaptee;
    public Adapter(Adaptee adaptee) { this.adaptee = adaptee; }
    public void request() { adaptee.specificRequest(); }
}

👉 适配器模式就像充电头转换器:iPhone 插口非得配个 Type-C 转换。


7. 代理模式(Proxy)

场景:控制访问,增加额外逻辑。

interface Service {
    void doWork();
}

class RealService implements Service {
    public void doWork() { System.out.println("业务逻辑"); }
}

class ProxyService implements Service {
    private RealService real;
    public ProxyService(RealService real) { this.real = real; }
    public void doWork() {
        System.out.println("前置校验");
        real.doWork();
        System.out.println("后置日志");
    }
}

👉 代理模式就是“请保镖”,你要见老板得先过代理。


8. 桥接模式(Bridge)

场景:将抽象与实现解耦,比如不同手机品牌和不同操作系统。

interface OS { void run(); }
class AndroidOS implements OS { public void run() { System.out.println("Android"); } }
class IOS implements OS { public void run() { System.out.println("iOS"); } }

abstract class Phone {
    protected OS os;
    public Phone(OS os) { this.os = os; }
    abstract void showInfo();
}

class Xiaomi extends Phone {
    public Xiaomi(OS os) { super(os); }
    public void showInfo() { System.out.print("小米手机,系统: "); os.run(); }
}

👉 桥接模式其实就是“插拔式组合”,能自由拼接。


9. 模板方法模式(Template Method)

场景:定义算法骨架,具体步骤由子类实现。

abstract class Game {
    abstract void init();
    abstract void play();
    abstract void end();

    public final void playGame() {
        init();
        play();
        end();
    }
}

class Chess extends Game {
    void init() { System.out.println("棋局开始"); }
    void play() { System.out.println("你来我往"); }
    void end() { System.out.println("棋局结束"); }
}

👉 模板方法就是“我来定流程,你来写细节”。


10. 装饰者模式(Decorator)

场景:动态地给对象添加功能。

interface Coffee {
    String getDescription();
    double cost();
}

class SimpleCoffee implements Coffee {
    public String getDescription() { return "黑咖啡"; }
    public double cost() { return 5; }
}

class MilkDecorator implements Coffee {
    private Coffee coffee;
    public MilkDecorator(Coffee coffee) { this.coffee = coffee; }
    public String getDescription() { return coffee.getDescription() + ", 加牛奶"; }
    public double cost() { return coffee.cost() + 2; }
}

👉 装饰者模式就像“奶茶加料”,黑咖啡加牛奶,再加珍珠,加到你钱包哭泣😭。


结语:套路不是束缚,而是解放

设计模式听起来像是“套路”,但写多了你会发现:它们不是给你添麻烦,而是帮你把未来的坑提前填上。

… …

文末

好啦,以上就是我这期的全部内容,如果有任何疑问,欢迎下方留言哦,咱们下期见。

… …

学习不分先后,知识不分多少;事无巨细,当以虚心求教;三人行,必有我师焉!!!

wished for you successed !!!


⭐️若喜欢我,就请关注我叭。

⭐️若对您有用,就请点赞叭。
⭐️若有疑问,就请评论留言告诉我叭。


版权声明:本文由作者原创,转载请注明出处,谢谢支持!

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。