设计模式——外观模式
看着别人学设计模式就是噌噌噌的带劲。虽然不是那么带劲,学习总是要开始的,今天就从外观模式的结构图开始。
外观模式(Facade),亦称"过程模式"。学校课程评价模式之一。美国教育学者斯泰克1967 年在所著《教育评价的外观》中提出。主张按照描述和判断资料来评价课程,关键的活动是在课程实施的全过程中进行观察和搜集意见,以了解人们对课程的不同看法。这种模式不限于检查教学的成果,重视描述和判断教学过程中各种复杂、动态的现象和事物。
这个外观类为子系统提供一个共同的对外接口
Clients
客户对象通过一个外观接口读写子系统中各接口的数据资源。
适用场景
(1)设计初期阶段,应该有意识的将不同层分离,层与层之间建立外观模式。
(2) 开发阶段,子系统越来越复杂,增加外观模式提供一个简单的调用接口。
(3) 维护一个大型遗留系统的时候,可能这个系统已经非常难以维护和扩展,但又包含非常重要的功能,为其开发一个外观类,以便新系统与其交互。
优点
(1)实现了子系统与客户端之间的松耦合关系。
(2)客户端屏蔽了子系统组件,减少了客户端所需处理的对象数目,并使得子系统使用起来更加容易。
Java代码
这是一个抽象的示例。一个客户"you"通过外观接口"computer"获取计算机内部复杂的系统信息。
/* Complex parts */
class CPU {
public void freeze() { ... }
public void jump(long position) { ... }
public void execute() { ... }
}
class Memory {
public void load(long position, byte[] data) {
...
}
}
class HardDrive {
public byte[] read(long lba, int size) {
...
}
}
/* Façade */
class Computer {
public void startComputer() {
cpu.freeze();
memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
cpu.jump(BOOT_ADDRESS);
cpu.execute();
}
}
/* Client */
class You {
public static void main(String[] args) {
Computer facade = new Computer();
facade.startComputer();
}
}
C#代码
// Facade pattern -- Structural example
using System;
namespace DoFactory.GangOfFour.Facade.Structural
{
// Mainapp test application
class MainApp
{
public static void Main()
{
Facade facade = new Facade();
facade.MethodA();
facade.MethodB();
// Wait for user
Console.Read();
}
}
// "Subsystem ClassA"
class SubSystemOne
{
public void MethodOne()
{
Console.WriteLine(" SubSystemOne Method");
}
}
// Subsystem ClassB"
class SubSystemTwo
{
public void MethodTwo()
{
Console.WriteLine(" SubSystemTwo Method");
}
}
// Subsystem ClassC"
class SubSystemThree
{
public void MethodThree()
{
Console.WriteLine(" SubSystemThree Method");
}
}
// Subsystem ClassD"
class SubSystemFour
{
public void MethodFour()
{
Console.WriteLine(" SubSystemFour Method");
}
}
// "Facade"
class Facade
{
SubSystemOne one;
SubSystemTwo two;
SubSystemThree three;
SubSystemFour four;
public Facade()
{
one = new SubSystemOne();
two = new SubSystemTwo();
three = new SubSystemThree();
four = new SubSystemFour();
}
public void MethodA()
{
Console.WriteLine("\nMethodA() ---- ");
one.MethodOne();
two.MethodTwo();
four.MethodFour();
}
public void MethodB()
{
Console.WriteLine("\nMethodB() ---- ");
two.MethodTwo();
three.MethodThree();
}
}
}
虽然这代码看起来很长,就这么的吧。下一篇希望自己懂得更多。