Facade外观模式(转载cnblogs)

Façade外观模式的结构



此模式特点:
客户端代码不需要关心子系统,它只需要关心聚合后所留下来的和外部交互的接口,而子系统是其他次子系统的聚合。此模式里面内部此次子系统的任何变化不会影响到聚合后的接口的变化。以达到“解耦”效果。

首先我们要实现三个子系统(WheelEngineBody):


 internal class Engine  //次子系统Engine 
        {

            public string EngineWork()
            {

                return "BMW's Engine is Working";

            }
            public string EngineStop()
            {

                return "BMW's Engine is stoped";

            }

        }

        internal class Wheel  //次子系统Wheel  
        {
            public string WheelCircumrotate()
            {
                return "Bmw' Wheel is Circumrotating";

            }

            public string WheelStop()
            {
                return "BMW'S Wheel is stoped";

            }

        }

        internal class Body  //子系统Body
        {

            public Wheel[] wheels = new Wheel[4];
            public Engine engine = new Engine();
            public Body()
            {

                for (int i = 0; i < wheels.Length; i++)
                {
                    wheels[i] = new Wheel();
                }

            }

        }

        public class CarFacade  //次子系统的聚合 

        {
            Body body = new Body();
            public void Run()
            {

                HttpContext.Current.Response.Write(body.engine.EngineWork());
                for (int i = 0; i < body.wheels.Length; i++)
                {

                    HttpContext.Current.Response.Write(body.wheels[i].WheelCircumrotate());

                }

            }

            public void Stop()
            {
                HttpContext.Current.Response.Write(body.engine.EngineStop());
                for (int i = 0; i < body.wheels.Length; i++)
                {

                    HttpContext.Current.Response.Write(body.wheels[i].WheelStop());

                }

            }


        }



前台实现聚合后的CarFacade接口


CarFacade xiao = new CarFacade();
        xiao.Run();
        xiao.Stop();



原文地址:https://www.cnblogs.com/xiaobaigang/p/870393.html