前进中的蜗牛

番茄大叔

水滴穿石,非一日之功;没有量变,何来质变。

外观模式(Facade Pattern)

模式定义

外观模式(Facade Pattern):外部与一个子系统的通信必须通过一个统一的外观对象进行,为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
其实就是专门定义一个类关联子系统,处理各个子系统的调用逻辑。

UML类图

  • Facade 外观角色 在客户端直接调用的角色,在外观角色中可以知道相关的(一个或者多个)子系统的功能和责任,
    它将所有从客户端发来的请求委派到相应的子系统去,传递给相应的子系统对象处理;实现:关联子系统角色,方便调用子系统的功能
  • SubSystem 子系统角色 具体子系统

代码结构

public static class FacadeApp
	{
		public static void Run()
		{
			Facade facade = new Facade();
			facade.Method();
		}
	}

	public class SubSystemOne
	{
		public void MethodOne()
		{
			Console.WriteLine("SubSystemOne MethodOne");
		}
	}

	public class SubSystemTwo
	{
		public void MethodTwo()
		{
			Console.WriteLine("SubSystemTwo MethodTwo");
		}
	}

	public class SubSystemThree
	{
		public void MethodThree()
		{
			Console.WriteLine("SubSystemThree MethodThree");
		}
	}

	public class Facade
	{
		private SubSystemOne _one;
		private SubSystemTwo _two;
		private SubSystemThree _three;

		public Facade()
		{
			_one = new SubSystemOne();
			_two = new SubSystemTwo();
			_three = new SubSystemThree();
		}

		public void Method()
		{
			Console.WriteLine("\nMethodA() ----- ");
			_one.MethodOne();
			_two.MethodTwo();
			_three.MethodThree();
		}
	}

情景模式

这里引用Learning Hard博客中的例子,这个例子太好的,上过学的都明白。学生选课

/// <summary>
    /// 以学生选课系统为例子演示外观模式的使用
    /// 学生选课模块包括功能有:
    /// 验证选课的人数是否已满
    /// 通知用户课程选择成功与否
    /// 客户端代码
    /// </summary>
    class Student
    {
        private static RegistrationFacade facade = new RegistrationFacade();

        static void Main(string[] args)
        {
            if (facade.RegisterCourse("设计模式", "Learning Hard"))
            {
                Console.WriteLine("选课成功");
            }
            else
            {
                Console.WriteLine("选课失败");
            }

            Console.Read();
        }
    }

    // 外观类
    public class RegistrationFacade
    {
        private RegisterCourse registerCourse;
        private NotifyStudent notifyStu;
        public RegistrationFacade()
        {
            registerCourse = new RegisterCourse();
            notifyStu = new NotifyStudent();
        }

        public bool RegisterCourse(string courseName, string studentName)
        {
            if (!registerCourse.CheckAvailable(courseName))
            {
                return false;
            }

            return notifyStu.Notify(studentName);
        }
    }

    #region 子系统
    // 相当于子系统A
    public class RegisterCourse
    {
        public bool CheckAvailable(string courseName)
        {
            Console.WriteLine("正在验证课程 {0}是否人数已满", courseName);
            return true;
        }
    }

    // 相当于子系统B
    public class NotifyStudent
    {
        public bool Notify(string studentName)
        {
            Console.WriteLine("正在向{0}发生通知", studentName);
            return true;
        }
    }
    #endregion
posted @ 2018-01-30 18:36  LoveTomato  阅读(257)  评论(0编辑  收藏  举报