java外观模式

来源:互联网 发布:搜狗推广账户怎么优化 编辑:程序博客网 时间:2024/05/17 04:15

外观模式,也叫做门面(Facade)模式,它为子系统中的各类(或结构与方法)提供一个简明一致的界面,隐藏子系统的复杂性,使得子系统更加容易使用。

从电脑启动和关闭来看吧,电脑启动时,其一些组成部件也要启动,关闭时,部件也要关闭,比如:CPU、内存、硬盘。

CPU类:

public class CPU {//CPU启动public void startup(){System.out.println("CPU startup");}//CPU关闭public void shutdown(){System.out.println("CPU shutdown");}}

Memory类:

public class Memory {//Memory启动public void startup(){System.out.println("Memory startup");}//Memory关闭public void shutdown(){System.out.println("Memory shutdown");}}

HardDrive类:

public class HardDrive {    //HardDrive 启动public void startup(){System.out.println("HardDrive startup");}//HardDrive 关闭public void shutdown(){System.out.println("HardDrive shutdown");}}

Computer类:

public class Computer {private CPU cpu;private Memory memory;private HardDrive hardDrive;public Computer(){this.cpu = new CPU();this.memory = new Memory();this.hardDrive = new HardDrive();}public void startup(){System.out.println("start the computer");this.cpu.startup();this.memory.startup();this.hardDrive.startup();System.out.println("start computer complete");}public void shutdown(){System.out.println("shutdown computer start");this.cpu.shutdown();this.memory.shutdown();this.hardDrive.shutdown();System.out.println("shutdown computer complete");}}

User类:

public class User {public static void main(String[] args) {Computer c = new Computer();c.startup();c.shutdown();}}

输出结果:

start the computer
CPU startup
Memory startup
HardDrive startup
start computer complete
shutdown computer start
CPU shutdown
Memory shutdown
HardDrive shutdown
shutdown computer complete

如果没有Computer类,那么CPU、Memory、HardDrive就得相互持有引用,如果修改一个类,其他的类都得做改动,而且将各个配置的方法统一放在Computer类的方法中,他们的执行顺序也很好控制。以后若要修改他们的关系,都可以在Computer类中修改,这样就起到了解耦的作用。

外观模式的要点:

1、外观模式为复杂子系统提供了一个简单接口,并不为子系统添加新的功能和行为。

2、外观模式实现了子系统与客户之间的松耦合关系。 

3、外观模式没有封装子系统的类,只是提供了简单的接口。 如果应用需要,它并不限制客户使用子系统类。因此可以再系统易用性与通用性之间选择。

4、外观模式注重的是简化接口,它更多的时候是从架构的层次去看整个系统,而并非单个类的层次。




0 0
原创粉丝点击