什么是外观模式?
例如:打开电脑时,在电脑的内部需要执行一下几步,即启动电源、主板、硬盘,最后启动操作系统:关闭电脑时需要执行
的步骤与之正好相反。
关键:1.意图 2.动机 3.适用性
package org.java.test;
/**
* @author Lee
* 功能:定义电源类 Power,并实现启动电源和关闭电源的方法
* @date:2018.11.27 22.23
*
* */
public class Power {
public void Connect(){
System.out.println("Power Connect");
}
public void Disconnect(){
System.out.println("Power Disconnect");
}
}
package org.java.test;
/**
* @author Lee
* 功能: MainBoard 主板类 ,定义主板开关的方法
* @date:2018.11.27 22.35
*
* */
public class MainBoard {
public void On(){
System.out.println("MainBoard On");
}
public void Off(){
System.out.println("MainBoard Off");
}
}
package org.java.test;
/**
* @author Lee
* 功能:HardDisk 硬盘
* @date:2018.11.27 22.38
*
* */
public class HardDisk {
public void Run(){
System.out.println("HardDisk Run");
}
public void Stop(){
System.out.println("HardDisk Stop");
}
}
package org.java.test;
/**
* @author Lee
* 功能: OperateionSystem 操作系统
* @date:2018.11.27 22:47
*
* */
public class OperateionSystem {
public void Startup(){
System.out.println("OperateionSystem Startup");
}
public void Shutdown(){
System.out.println("OperateionSystem Shutdown");
}
}
package org.java.test;
/**
* @author Lee
* @param:power 电源
* mainBoard 主板
* hardDisk 硬盘
* operateionSystem 操作系统
* @date:2018.11.27 22:51
*
*
* */
public class Computer {
Power power;
MainBoard mainBoard;
HardDisk hardDisk;
OperateionSystem operateionSystem;
public Computer(Power power, MainBoard mainBoard, HardDisk hardDisk, OperateionSystem operateionSystem) {
super();
this.power = power;
this.mainBoard = mainBoard;
this.hardDisk = hardDisk;
this.operateionSystem = operateionSystem;
}
//启动计算机
public void StartUp(){
this.power.Connect();
this.hardDisk.Run();
this.operateionSystem.Startup();
}
//关闭计算机
public void Shutdown(){
this.hardDisk.Stop();
this.mainBoard.Off();
this.power.Disconnect();
}
}
package org.java.test;
/**
* @author Lee
* 功能:测试
* @date:2018.11.27 23.08
*
* */
public class Program {
public static void main(String[] args) {
Power power=new Power(); //创建电源对象
MainBoard mainBoard=new MainBoard(); //创建主板对象
HardDisk hardDisk=new HardDisk(); //创建硬盘对象
OperateionSystem operateionSystem=new OperateionSystem(); //创建操作系统对象
Computer computer=new Computer(power, mainBoard, hardDisk, operateionSystem);//创建计算机对象
System.out.println("打开电脑");
computer.StartUp();
System.out.println("关闭电脑");
computer.Shutdown();
}
}