外观模式(Facade Pattern):外部与一个子系统的通讯必须经过一个统一的外观对象进行,为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。外观模式又称为门面模式,它是一种对象结构型模式。spa
根据“单一职责原则”,在软件中将一个系统划分为若干个子系统有利于下降整个系统的复杂性,一个常见的设计目标是使子系统间的通讯和相互依赖关系达到最小,而达到该目标的途径之一就是引入一个外观对象,它为子系统的访问提供了一个简单而单一的入口。 -外观模式也是“迪米特法则”的体现,经过引入一个新的外观类能够下降原有系统的复杂度,同时下降客户类与子系统类的耦合度。 - 外观模式要求一个子系统的外部与其内部的通讯经过一个统一的外观对象进行,外观类将客户端与子系统的内部复杂性分隔开,使得客户端只须要与外观对象打交道,而不须要与子系统内部的不少对象打交道。 -外观模式的目的在于下降系统的复杂程度。 -外观模式从很大程度上提升了客户端使用的便捷性,使得客户端无须关心子系统的工做细节,经过外观角色便可调用相关功能。设计
外观模式包含以下角色:code
Facade.cs对象
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Facade 8 { 9 public interface Facade 10 { 11 void speak(); 12 } 13 }
SystemA.cs、SystemB.cs、SystemC.csblog
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Facade 8 { 9 public class SystemA:Facade 10 { 11 12 public void speak() 13 { 14 Console.WriteLine("我是系统A"); 15 } 16 } 17 }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Facade 8 { 9 public class SystemB : Facade 10 { 11 public void speak() 12 { 13 Console.WriteLine("我是系统B"); 14 } 15 } 16 }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Facade 8 { 9 public class SystemC : Facade 10 { 11 public void speak() 12 { 13 Console.WriteLine("我是系统C"); 14 } 15 } 16 }
ShapeMaker.cs接口
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Facade 8 { 9 public class ShapeMaker 10 { 11 private Facade systemA; 12 private Facade systemB; 13 private Facade systemC; 14 public ShapeMaker() 15 { 16 systemA = new SystemA(); 17 systemB = new SystemB(); 18 systemC = new SystemC(); 19 } 20 public void operationA() 21 { 22 systemA.speak(); 23 } 24 public void operationB() 25 { 26 systemB.speak(); 27 } 28 public void operationC() 29 { 30 systemC.speak(); 31 } 32 } 33 }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Facade 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 ShapeMaker shapeMaker = new ShapeMaker(); 14 shapeMaker.operationA(); 15 shapeMaker.operationB(); 16 shapeMaker.operationC(); 17 Console.ReadKey(); 18 } 19 } 20 }