java结构型设计_Java设计模式(9)结构型:外观模式

(一)模式概念

外观模式是指为定义一个高层接口,这个接口使得子系统更加容易使用。换句话说就是客户对象通过一个接口读写子系统中各接口的数据资源,降低了类类之间的耦合度。以计算机开机和关机为例,如计算机开机会先启动CPU,继而启动缓存和硬盘,CPU、缓存和硬盘之间的启动有先后交互关系。这时可以使用装饰模式,定义一个高层接口,来解耦3个组件之间的关系。

(二)Demo

CPU实体类:

public class CPU {

public void startup() {

System.out.println("cpu startup!");

}

public void shutdown() {

System.out.println("cpu shutdown!");

}

}

Disk实体类:

public class Disk {

public void startup() {

System.out.println("disk startup!");

}

public void shutdown() {

System.out.println("disk shutdown!");

}

}

Memory实体类:

public class Memory {

public void startup() {

System.out.println("memory startup!");

}

public void shutdown() {

System.out.println("memory shutdown!");

}

}

ComputerFacade电脑实体类:

public class ComputerFacade {

private CPU cpu;

private Memory memory;

private Disk disk;

public ComputerFacade() {

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!");

}

}

执行过程:

ComputerFacade computer = new ComputerFacade();

computer.startup();

computer.shutdown();

执行结果:

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!

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页