設計模式——9外觀模式(Facade)

inzaghi1984發表於2017-12-10

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類裡,這樣就起到了解耦的作用,這,就是外觀模式!


相關文章