设计模式 - 9) 外观模式

比如开一台设备需要按顺序给显示器通电、亮灯、发出声音。
在使用外观模式前,客户端直接调用通电、亮灯、发出声音。
在这样的情况下,后续如果流程发生变化,比如不需要发出声音或声音需要在亮灯之前,就需要修改客户端的代码,如果客户端多处调用,就需要修改多处。

public class SubSystemOne
{
    public void MethodOne()
    {
        Console.WriteLine("子系统方法一");
    }
}

public class SubSystemTwo
{
    public void MethodTwo()
    {
        Console.WriteLine("子系统方法二");
    }
}

public class SubSystemThree
{
    public void MethodThree()
    {
        Console.WriteLine("子系统方法三");
    }
}

// 业务调用
SubSystemOne one = new SubSystemOne();
one.MethodOne();            
SubSystemTwo two = new SubSystemTwo();
two.MethodTwo();

使用外观模式以后,业务系统在启动的时候只需要按下开关,由开关去触发通电、亮灯、发出声音的操作。业务端的代码只需要按下开关。后续如果流程发生变化,只需要修改 Facade 类。

public class SubSystemOne
{
    public void MethodOne()
    {
        Console.WriteLine("子系统方法一");
    }
}

public class SubSystemTwo
{
    public void MethodTwo()
    {
        Console.WriteLine("子系统方法二");
    }
}

public class SubSystemThree
{
    public void MethodThree()
    {
        Console.WriteLine("子系统方法三");
    }
}

public class Facade
{
    SubSystemOne one;
    SubSystemTwo two;
    SubSystemThree three;
    
    public Facade()
    {
        one = new SubSystemOne();
        two = new SubSystemTwo();
        three = new SubSystemThree();
    }

    public void MethodA()
    {
        Console.WriteLine("\n方法组A:");
        one.MethodOne();
        two.MethodTwo();            
    }

    public void MethodB()
    {
        Console.WriteLine("\n方法组B:");
        two.MethodTwo();
        three.MethodThree();
    }
}

// 业务调用
Facade f = new Facade();
f.MethodA();            
f.MethodB();

可用于如果 新系统 需要调用 遗留代码 中逻辑比较复杂的代码时,可使用外观模式,由 Facede 类去封装复杂的逻辑,并提供简单的接口给新系统使用。

posted @ 2020-12-15 23:52  鑫茂  阅读(63)  评论(0编辑  收藏  举报