当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 深入理解设计模式(24):外观模式

深入理解设计模式(24):外观模式

2019年04月11日  | 移动技术网IT编程  | 我要评论

一、什么是外观模式

定义:为子系统中的一组接口提供一个一致的界面,用来访问子系统中的一群接口。

 

外观模式组成:

  facade:负责子系统的的封装调用

  subsystem classes:具体的子系统,实现由外观模式facade对象来调用的具体任务

二、外观模式的使用场景

  1、设计初期阶段,应该有意识的将不同层分离,层与层之间建立外观模式;
  2、开发阶段,子系统越来越复杂,增加外观模式提供一个简单的调用接口;
  3、维护一个大型遗留系统的时候,可能这个系统已经非常难以维护和扩展,但又包含非常重要的功能,为其开发一个外观类,以便新系统与其交互。

三、外观模式的优缺点

优点:

  1、实现了子系统与客户端之间的松耦合关系;
  2、客户端屏蔽了子系统组件,减少了客户端所需处理的对象数目,并使得子系统使用起来更加容易。

缺点:

  1、不符合开闭原则,如果要修改某一个子系统的功能,通常外观类也要一起修改;
  2、没有办法直接阻止外部不通过外观类访问子系统的功能,因为子系统类中的功能必须是公开的(根据需要决定是否使用internal访问级别可解决这个缺点,但外观类需要和子系统类在同一个程序集内)。

四、外观模式的实现

先写出四个子系统的类

class subsystemone
{
    public void methodone()
    {
        console.writeline("子系统方法一");
    }
}
class subsystemtwo
{
    public void methodtwo()
    {
        console.writeline("子系统方法二");
    }
}
class subsystemthree
{
    public void methodthree()
    {
        console.writeline("子系统方法三");
    }
}
class subsystemfour
{
    public void methodfour()
    {
        console.writeline("子系统犯法四");
    }
}

引入外观类,减少子系统类之间的交互

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("\n方法组合a()---");
        one.methodone();
        two.methodtwo();
        four.methodfour();
    }
    public void methodb()
    {
        console.writeline("\n方法组b()---");
        two.methodtwo();
        three.methodthree();
    }
}

客户端代码:

static void main(string[] args)
{
    facade facade = new facade();
    facade.methoda();
    facade.methodb();
    console.read();
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网