设计模式——9外观模式(Facade)

简介: 外观模式(Facade)

9、外观模式(Facade)
外观模式是为了解决类与类之家的依赖关系的,像spring一样,可以将类和类之间的关系配置到配置文件中,而外观模式就是将他们的关系放在一个Facade类中,降低了类类之间的耦合度,该模式中没有涉及到接口。

我们先看下实现类:
[java] view plaincopy

  1. public class CPU {
  2. public void startup(){
  3. System.out.println("cpu startup!");
  4. }
  5. public void shutdown(){
  6. System.out.println("cpu shutdown!");
  7. }
  8. }
    [java] view plaincopy
  9. public class Memory {
  10. public void startup(){
  11. System.out.println("memory startup!");
  12. }
  13. public void shutdown(){
  14. System.out.println("memory shutdown!");
  15. }
  16. }
    [java] view plaincopy
  17. public class Disk {
  18. public void startup(){
  19. System.out.println("disk startup!");
  20. }
  21. public void shutdown(){
  22. System.out.println("disk shutdown!");
  23. }
  24. }
    [java] view plaincopy
  25. public class Computer {
  26. private CPU cpu;
  27. private Memory memory;
  28. private Disk disk;
  29. public Computer(){
  30. cpu = new CPU();
  31. memory = new Memory();
  32. disk = new Disk();
  33. }
  34. public void startup(){
  35. System.out.println("start the computer!");
  36. cpu.startup();
  37. memory.startup();
  38. disk.startup();
  39. System.out.println("start computer finished!");
  40. }
  41. public void shutdown(){
  42. System.out.println("begin to close the computer!");
  43. cpu.shutdown();
  44. memory.shutdown();
  45. disk.shutdown();
  46. System.out.println("computer closed!");
  47. }
  48. }
    User类如下:

[java] view plaincopy

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

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类里,这样就起到了解耦的作用,这,就是外观模式!

目录
相关文章
|
29天前
|
设计模式 存储 uml
C++ 设计模式实战:外观模式和访问者模式的结合使用,派生类访问基类的私有子系统
C++ 设计模式实战:外观模式和访问者模式的结合使用,派生类访问基类的私有子系统
27 1
|
3月前
|
设计模式
设计模式-外观模式
设计模式-外观模式
31 0
|
3月前
|
设计模式 Go 开发工具
Golang设计模式——03外观模式
Golang设计模式——03外观模式
21 0
|
3月前
|
设计模式 Java 应用服务中间件
设计模式 -结构型模式_门面模式(外观模式) Facade Pattern 在开源软件中的应用
设计模式 -结构型模式_门面模式(外观模式) Facade Pattern 在开源软件中的应用
30 1
|
30天前
|
设计模式 uml
设计模式之外观模式
设计模式之外观模式
|
1月前
|
设计模式 应用服务中间件 智能硬件
【设计模式】外观模式
【设计模式】外观模式
|
3月前
|
设计模式 Java
聊聊Java设计模式-外观模式
外观(Facade)模式,又叫做门面模式,是一种通过为多个复杂的子系统提供一个一致的接口,使这些子系统更加容易被访问的模式。
35 1
聊聊Java设计模式-外观模式
|
3月前
|
设计模式
设计模式 | 门面模式 Facade
设计模式 | 门面模式 Facade
18 0
|
3月前
|
设计模式 前端开发 数据库
【设计模式】之外观模式
外观模式是一种简化复杂系统接口的设计模式,在前端开发中有着广泛的应用。它可以帮助我们封装复杂的子系统,并提供一个简单易用的接口给客户端。通过使用外观模式,我们可以提高代码的可维护性、可读性和扩展性。但是需要注意避免过度使用外观模式,以免造成不必要的性能问题。
41 1
|
4月前
|
设计模式
二十三种设计模式全面解析-解锁外观模式的神秘面纱:深入探讨外观模式的魔力
二十三种设计模式全面解析-解锁外观模式的神秘面纱:深入探讨外观模式的魔力