看下图:
A 方案的问题在于组件的客户和组件中各种复杂的子系统有了过多的耦合,随着外部客户程序和各子系统的演化,这种过多的耦合面临很多变化的挑战。
解决思路:
简化外部客户程序和系统间的交互接口;将外部客户程序的演化和内部子系统的变化之间的依赖相互解耦。
示例代码:
internal
class
Wheel
{
public void WAction1()
{
}
public void WAction2()
{
}
}
internal class Engine
{
public void EAction1()
{
}
public void EAction2()
{
}
}
internal class Bodywork
{
public void BAction1()
{
}
public void BAction2()
{
}
}
internal class Controller
{
public void CAction1()
{
}
public void CAction2()
{
}
}
public class TankFacade
{
Wheel[] wheels = new Wheel[ 4 ];
Engine [] engine = new Engine[ 4 ];
Bodywork bodywork = new Bodywork();
Controller controller = new Controller();
public void Start()
{
//
controller.CAction1();
}
public void Stop()
{
}
public void Run()
{
}
public void Shot()
{
}
}
public static void Main()
{
TankFacade tf = new TankFacade();
tf.Run();
tf.Start();
tf.Shot();
tf.Stop();
}
Facade模式的几个要点
{
public void WAction1()
{
}
public void WAction2()
{
}
}
internal class Engine
{
public void EAction1()
{
}
public void EAction2()
{
}
}
internal class Bodywork
{
public void BAction1()
{
}
public void BAction2()
{
}
}
internal class Controller
{
public void CAction1()
{
}
public void CAction2()
{
}
}
public class TankFacade
{
Wheel[] wheels = new Wheel[ 4 ];
Engine [] engine = new Engine[ 4 ];
Bodywork bodywork = new Bodywork();
Controller controller = new Controller();
public void Start()
{
//
controller.CAction1();
}
public void Stop()
{
}
public void Run()
{
}
public void Shot()
{
}
}
public static void Main()
{
TankFacade tf = new TankFacade();
tf.Run();
tf.Start();
tf.Shot();
tf.Stop();
}
• 从客户程序的角度来看, Facade模式不仅简化了整个组件系统的接口,同时对于组件内部与外部客户程序来说,从某种程度上也达到了一种“解耦”的效果——内部子系统的任何变化不会影响到Façade接口的变化。
• Façade设计模式更注重从架构的层次去看整个系统,而不是单个类的层次。Façade很多时候更是一种架构设计模式。
• 注意区分Façade模式、Adapter模式、Bridge模式与Decorator模式。Façade模式注重简化接口,Adapter模式注重转换接口,Bridge模式注重分离接口(抽象)与其实现,Decorator模式注重稳定接口的前提下为对象扩展功能。