C# 外观模式

 外观模式(Facade Pattern)

介绍

定义:  为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。使用外观模式时,创建了一个统一的类,用来包装子类系统中一个或多个复杂的类,客户端可以通过外观类来调用内部子系统中方法,从而外观模式让客户和子系统之间避免了紧耦合。

优点: 1、减少系统相互依赖。 2、提高灵活性。 3、提高了安全性。

缺点:不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。

何时使用: 1、客户端不需要知道系统内部的复杂联系,整个系统只需提供一个"接待员"即可。 2、定义系统的入口。

实现

例如一个学校校长, 要求了解一个班级学生的纪律信息和学习信息,我们可以规定

班长------>整理班级纪律信息

团支书------>整理班级学习信息

班长和团支书将各自信息传递给老师,

老师将全部信息------->校长

 操作如图

 代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FacadeTest : MonoBehaviour {
    // Use this for initialization
    void Start () {
        HeadMaster headMaster = new HeadMaster();
        headMaster.OrderTeacherDoSummary();
    }
    // Update is called once per frame
    void Update () { 
    }
}
/// <summary>
/// 校长类
/// </summary>
public class HeadMaster
{
    private Teacher teacher;
    public HeadMaster()
    {
        teacher = new Teacher();
    }
    public void OrderTeacherDoSummary()
    {
        teacher.SubmitStudentInfomation();
    }
}
/// <summary>
/// 老师类
/// </summary>
public class Teacher
{
    private Monitor monitor;
    private LeagueSecretary leagueSecretary;
    public Teacher()
    {
        monitor = new Monitor();
        leagueSecretary = new LeagueSecretary();
    }
    public void SubmitStudentInfomation()
    {
        monitor.CollectStudentRuleInfomation();
        leagueSecretary.CollectStudentStudyInfomation();
    }
}
/// <summary>
/// 班长类
/// </summary>
public class Monitor
{
    public void CollectStudentRuleInfomation()
    {
        Debug.Log("班长统计班里纪律信息:整理材料");
    }
}
/// <summary>
/// 团支书类
/// </summary>
public class LeagueSecretary
{
    public void CollectStudentStudyInfomation()
    {
        Debug.Log("团支书统计班里学习信息:整理材料");
    }
}
原文地址:https://www.cnblogs.com/lk95/p/9991236.html