设计模式-外观模式

定义:

 隐藏了系统的复杂性,并向客户端提供了一个可以访问系统的接口。

模式结构和代码示例

简单来说,该模式就是把一些复杂的流程封装成一个接口供给外部用户更简单的使用。这个模式中,设计到3个角色。

  1).门面角色:外观模式的核心。它被客户角色调用,它熟悉子系统的功能。内部根据客户角色的需求预定了几种功能的组合。(客户调用,同时自身调用子系统功能)

  2).子系统角色:  实现了子系统的功能。它对客户角色和Facade时未知的。它内部可以有系统内的相互交互,也可以由供外界调用的接口。(实现具体功能)

  3).客户角色:  通过调用Facede来完成要实现的功能(调用门面角色)。

举例(每个Computer都有CPU、Memory、Disk。在Computer开启和关闭的时候,相应的部件也会开启和关闭),类图如下:

 子类系统:

public class CPU {
 
	public void start() {
		System.out.println("cpu is start...");
	}
 
	public void shutDown() {
		System.out.println("CPU is shutDown...");
	}
}
 
public class Disk {
	public void start() {
		System.out.println("Disk is start...");
	}
 
	public void shutDown() {
		System.out.println("Disk is shutDown...");
	}
}
 
public class Memory {
	public void start() {
		System.out.println("Memory is start...");
	}
 
	public void shutDown() {
		System.out.println("Memory is shutDown...");
	}
}

门面类Facade

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 start() {
		System.out.println("Computer start begin");
		cpu.start();
		disk.start();
		memory.start();
		System.out.println("Computer start end");
	}
 
	public void shutDown() {
		System.out.println("Computer shutDown begin");
		cpu.shutDown();
		disk.shutDown();
		memory.shutDown();
		System.out.println("Computer shutDown end...");
	}
}

客户角色

public class Client {
 
	public static void main(String[] args) {
		Computer computer = new Computer();
		computer.start();
		System.out.println("=================");
		computer.shutDown();
	}
 
}

 优点

- 松散耦合

  使得客户端和子系统之间解耦,让子系统内部的模块功能更容易扩展和维护;

- 简单易用

  客户端根本不需要知道子系统内部的实现,或者根本不需要知道子系统内部的构成,它只需要跟Facade类交互即可。

- 更好的划分访问层次

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值