`

设计模式之门面模式

阅读更多
门面模式又叫外观模式。
为子系统的一组接口提供一个一致的门面,定义了更高层的接口,使子系统更方便使用。
所有客户端直接与门面类进行交互,这样就减少了客户端与子系统之间的耦合。
组成:门面角色,被客户端调用,它熟悉子系统的功能,根据客户的需求提供了一些供客户端使用的功能组合。
     子系统角色:实现了子系统的功能,对它而言不知道facade的存在。
     客户端角色:调用facade来完成需要实现的功能。
     facade的一个典型的实例就是数据库链接,如我们每次访问数据库都是建立conn,获取statement,执行sql,得到statement,我们可以对这些步骤进行一个
     抽象,然后把端口暴露给上层.
优点:对客户端而言,它屏蔽了子系统。使得子系统不可见。降低了客户端与子系统的耦合。
     在大型软件中降低编译依赖性非常重要,使用facade后编译一个修改了的子系统也不需要编译其他子系统。
实例:
public class Camera
{
  public void TurnOn()
  {
    Console.WriteLine("Turning on the camera.");
  }

  public void TurnOff()
  {
    Console.WriteLine("Turning off the camera.");
  }

  public void Rotate(int degrees)
  {
    Console.WriteLine("Rotating the camera by {0} degrees.", degrees);
  }
}

public class Light
{

  public void TurnOff()
  {
    Console.WriteLine("Turning on the light.");
  }

  public void TurnOn()
  {
    Console.WriteLine("Turning off the light.");
  }

  public void ChangeBulb()
  {
    Console.WriteLine("changing the light-bulb.");
  }
}

public class Sensor
{
  public void Activate()
  {
    Console.WriteLine("Activating the sensor.");
  }

  public void Deactivate()
  {
    Console.WriteLine("Deactivating the sensor.");
  }

  public void Trigger()
  {
    Console.WriteLine("The sensor has triggered.");
  }
}

public class Alarm
{

  public void Activate()
  {
    Console.WriteLine("Activating the alarm.");
  }

  public void Deactivate()
  {
    Console.WriteLine("Deactivating the alarm.");
  }

  public void Ring()
  {
    Console.WriteLine("Ringing the alarm.");
  }

  public void StopRing()
  {
    Console.WriteLine("Stop the alarm.");
  }
}

public class SecurityFacade
{
  private static Camera camera1, camera2;
  private static Light light1, light2, light3;
  private static Sensor sensor;
  private static Alarm alarm;

  static SecurityFacade()
  {
    camera1 = new Camera();
    camera2 = new Camera();
    light1 = new Light();
    light2 = new Light();
    light3 = new Light();
    sensor = new Sensor();
    alarm = new Alarm();
  }
 
  public void Activate()
  {
    camera1.TurnOn();
    camera2.TurnOn();
    light1.TurnOn();
    light2.TurnOn();
    light3.TurnOn();
    sensor.Activate();
    alarm.Activate();
  }

  public void Deactivate()
  {
    camera1.TurnOff();
    camera2.TurnOff();
    light1.TurnOff();
    light2.TurnOff();
    light3.TurnOff();
    sensor.Deactivate();
    alarm.Deactivate();
  }
}

public class Client
{
  private static SecurityFacade security;

  public static void Main( string[] args )
  {
    security = new SecurityFacade();
    security.Activate();
    Console.WriteLine("\n--------------------\n");
    security.Deactivate();
  }
注释:使用门面模式后,根据客户端的需求直接暴露给客户端所需要的接口。如上客户端只需要调用facade的两个操作就可以完成想要的功能。
     否则客户端需要创建出全部子系统的实例,然后很多进行操作才会达到使用门面模式的效果。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics