Java 之 23 种设计模式解析——9、外观模式(Facade)

本文通过计算机启动过程示例,介绍外观模式如何降低类间耦合度。通过创建Computer类统一管理CPU、Memory和Disk的启动与关闭操作,简化客户端使用流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

9、外观模式(Facade)

外观模式是为了解决类与类之家的依赖关系的,像spring一样,可以将类和类之间的关系配置到配置文件中,而外观模式就是将他们的关系放在一个Facade类中,降低了类类之间的耦合度,该模式中没有涉及到接口,看下类图:(我们以一个计算机的启动过程为例)

我们先看下实现类:

 public class CPU {
	public void startup(){
System.out.println("cpu startup!");
	}

	public void shutdown(){
	System.out.println("cpu shutdown!");
	}
 }

 public class Memory {

	public void startup(){
	System.out.println("memory startup!");
	}

	public void shutdown(){
	System.out.println("memory shutdown!");
	}
}

 public class Disk {

	public void startup(){
	System.out.println("disk startup!");
	}

public void shutdown(){
System.out.println("disk shutdown!");
	}
 }

 public class Computer {
	private CPU cpu;
	private Memory memory;
	private Disk disk;

	public Computer(){
	cpu = new CPU();
	memory = new Memory();
	disk = new Disk();
	}

	public void startup(){
	System.out.println("start the computer!");
	cpu.startup();
	memory.startup();
	disk.startup();
	System.out.println("start computer finished!");
	}

	public void shutdown(){
	System.out.println("begin to close the computer!");
	cpu.shutdown();
	memory.shutdown();
	disk.shutdown();
	System.out.println("computer closed!");
	}
 }

User类如下:

1. public class User {
2.
3.	public static void main(String[] args) {
4.	Computer computer = new Computer();
5.	computer.startup();
6.	computer.shutdown();
7.	}
8. }

输出:

start the computer!
cpu startup!
memory startup!
disk startup!
start computer finished!
begin to close the computer!
cpu shutdown!
memory shutdown!
disk shutdown!
computer closed!

如果我们没有Computer类,那么,CPU、Memory、Disk他们之间将会相互持有实例,产生关系,这样会造成严重的依赖,修改一个类,可能会带来其他类的修改,这不是我们想要看到的,有了Computer类,他们之间的关系被放在了Computer类里,这样就起到了解耦的作用,这,就是外观模式!

目录:(点击进入相应页面)

概述、六大原则

一、创建模式

0、简单工厂模式

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

2、抽象工厂模式

3、单例模式(Singleton)

4、建造者模式(Builder)

5、原型模式(Prototype)

二、结构模式(7种)

6、适配器模式

7、装饰模式(Decorator)

8、代理模式(Proxy)

9、外观模式(Facade)

10、桥接模式(Bridge)

11、组合模式(Composite

12、享元模式(Flyweight)

三、关系模式(11种)

13、策略模式(strategy)

14、模板方法模式(Template Method)

15、观察者模式(Observer)

16、迭代子模式(Iterator)

17、责任链模式(Chain of Responsibility)

18、命令模式(Command)

19、备忘录模式(Memento

20、状态模式(State)

21、访问者模式(Visitor)

22、中介者模式(Mediator)

23、解释器模式(Interpreter)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值