1. 介绍
也成为外观模式,外观模式是一种结构型设计模式,它通过提供一个简化的统一接口,来隐藏子系统的复杂性,使客户端更容易使用系统功能。
2. 核心思想
封装复杂性
将多个子系统(类、接口、模块)的交互逻辑封装在一个高层接口(外观类)中,客户端只需调用这个接口,无需了解底层细节。
类比:就像电脑的“开机键”,按下后自动完成BIOS自检、加载系统、启动服务等复杂过程,用户无需关心内部如何运作。
解耦客户端与子系统
客户端只依赖外观类,不直接调用子系统,降低耦合度。
子系统内部修改时,只要外观接口不变,客户端代码就无需调整。
提供易用的入口
适用于简化复杂系统(如框架、库、遗留代码)的调用方式。
适用场景
✅ 简化复杂系统(如调用多个API、第三方服务)
✅ 为遗留代码提供清晰接口(避免直接修改混乱的旧代码)
✅ 分层设计(如MVC框架中的Controller层封装Model和View的交互)
✅ 减少客户端依赖(客户端只需知道外观类,不用了解所有子系统)
与其他模式的区别
外观模式 vs. 中介者模式(Mediator)
外观模式:单向封装(客户端→子系统),侧重简化调用。
中介者模式:双向协调(对象间互相通信),侧重解耦多对象交互。
外观模式 vs. 适配器模式(Adapter)
外观模式:提供新接口,优化使用体验。
适配器模式:转换旧接口,解决兼容性问题。
3. 代码示例
/// <summary>
/// 通过一个类把一系列功能封装起来 然后统一调用
/// </summary>
public class Facade
{
static void Main()
{
BattleFacade battleFacade = new BattleFacade();
battleFacade.PlayerAttack("Goblin");
}
}
public class AnimationSystem
{
public void PlayAttackAnimation(string attacker)
{
Console.WriteLine($"{attacker} 播放攻击动画");
}
}
public class AudioSystem
{
public void PlaySound(string soundName)
{
Console.WriteLine($"播放音效:{soundName}");
}
}
public class DamageSystem
{
public void ApplyDamage(string target, int amount)
{
Console.WriteLine($"{target} 扣除 {amount} 点生命");
}
}
public class EffectSystem
{
public void ShowEffect(string effectName)
{
Console.WriteLine($"显示特效:{effectName}");
}
}
public class UISystem
{
public void UpdateEnemyHealthBar(string target)
{
Console.WriteLine($"更新 {target} 的血条 UI");
}
}
/// <summary>
/// 门面类(Facade)
/// </summary>
public class BattleFacade
{
private AnimationSystem animationSystem = new AnimationSystem();
private AudioSystem audioSystem = new AudioSystem();
private DamageSystem damageSystem = new DamageSystem();
private EffectSystem effectSystem = new EffectSystem();
private UISystem uiSystem = new UISystem();
public void PlayerAttack(string enemy)
{
animationSystem.PlayAttackAnimation("Player");
audioSystem.PlaySound("attack");
damageSystem.ApplyDamage(enemy, 10);
effectSystem.ShowEffect("Slash");
uiSystem.UpdateEnemyHealthBar(enemy);
}
}