设计模式是软件开发中的工具箱,它们提供了经过验证的解决方案,帮助我们设计出结构清晰、易于维护、可扩展的系统。下面我为你介绍几种常用且重要的设计模式,并用通俗易懂的语言逐步讲解。
一、设计模式的分类
设计模式大致可以分为三类:
- 创建型模式:关注对象的实例化与创建方式
- 结构型模式:关注类或对象之间的组合
- 行为型模式:关注对象之间的交互与职责分配
二、常用设计模式详细介绍
1. 单例模式(Singleton Pattern)
目的:确保一个类只有一个实例,并提供全局访问点。
通俗例子:手机的“状态中心”或“配置信息”,只需要一份就够了,避免重复创建和维护多个副本。
实现要点:
- 构造函数私有化,防止在外部用
new
创建实例 - 提供静态方法返回唯一实例
- 在多线程环境下要确保线程安全(使用同步锁或静态内部类)
示意代码(伪码):
class Singleton {
private static Singleton instance;
private Singleton() { } //私有化构造函数
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2. 工厂方法模式(Factory Method Pattern)
目的:定义一个创建对象的接口,但由子类决定实例化哪个类。用“工厂”来封装创建过程。
通俗例子:你去快餐店点餐,不同的快餐(汉堡、薯条)由不同工厂制作,你只知道要点,但具体做法由不同工厂完成。
实现要点:
- 抽象“工厂”接口或基类,定义创建方法
- 具体工厂子类实现具体的实例化逻辑
- 客户端通过工厂接口获得产品对象,不关心具体实现
示意代码(伪码):
复制代码
interface Animal {
void speak();
}
class Dog implements Animal {
public void speak() { System.out.println("汪汪!"); }
}
class Cat implements Animal {
public void speak() { System.out.println("喵喵!"); }
}
interface AnimalFactory {
Animal createAnimal();
}
class DogFactory implements AnimalFactory {
public Animal createAnimal() { return new Dog(); }
}
class CatFactory implements AnimalFactory {
public Animal createAnimal() { return new Cat(); }
}
// 使用
AnimalFactory factory = new DogFactory();
Animal animal = factory.createAnimal();
animal.speak(); //输出汪汪!
3. 抽象工厂模式(Abstract Factory Pattern)
目的:提供一系列相关或依赖的对象的创建接口,但不指定具体类。
通俗例子:你喜欢的“家具套装”,比如“现代风格沙发+现代风格茶几”就是一套。不同风格的家具组合由不同的工厂创建。
实现要点:
- 定义抽象工厂接口,提供多个产品(比如“椅子”、“桌子”)的创建方法
- 每个子工厂实现一种风格(现代、古典)
示意代码(伪码):
interface FurnitureFactory {
Chair createChair();
Table createTable();
}
class ModernFurnitureFactory implements FurnitureFactory {
public Chair createChair() { return new ModernChair(); }
public Table createTable() { return new ModernTable(); }
}
class ClassicFurnitureFactory implements FurnitureFactory {
public Chair createChair() { return new ClassicChair(); }
public Table createTable() { return new ClassicTable(); }
}
4. 观察者模式(Observer Pattern)
目的:定义对象间的一对多依赖关系,当对象状态变化时,所有依赖于它的对象都会得到通知。
通俗例子:天气预报网站(被观察者)通知多个显示设备(观察者)天气变化信息。
实现要点:
- 被观察者维护订阅者(观察者)列表
- 发生变化时,主动通知所有观察者
示意代码(伪码):
复制代码
interface Observer {
void update(String message);
}
class WeatherStation {
private List<Observer> observers = new ArrayList<>();
public void attach(Observer observer) { observers.add(observer); }
public void detach(Observer observer) { observers.remove(observer); }
public void notifyObservers(String message) {
for (Observer o : observers) {
o.update(message);
}
}
}
class TV implements Observer {
public void update(String message) {
System.out.println("电视显示天气:" + message);
}
}
5. 策略模式(Strategy Pattern)
目的:定义一系列算法,把它们封装起来,使它们可以互相替换,客户端可以在运行时选择不同策略。
通俗例子:你在打车时可以选择不同的支付方式(支付宝、微信、现金),每个支付策略不同,但操作方法统一。
实现要点:
- 定义策略接口
- 不同策略实现
- 上下文类维护一个策略对象,供调用
示意代码(伪码):
复制代码
interface PaymentStrategy {
void pay(int amount);
}
class AlipayStrategy implements PaymentStrategy {
public void pay(int amount) { System.out.println("支付宝支付" + amount); }
}
class WechatStrategy 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 pay(int amount) {
strategy.pay(amount);
}
}
// 使用
PaymentContext context = new PaymentContext(new AlipayStrategy());
context.pay(100);
三、总结
- 单例模式:确保全局唯一实例
- 工厂模式:封装对象创建
- 抽象工厂:创建一系列相关对象
- 观察者模式:一对多通知
- 策略模式:封装算法,动态切换
这些都是开源软件、框架中非常常见的“基础工具”。理解它们的思想,有助于你设计出更加优雅和健壮的程序。