C# 外观模式(Facade)
该模式主要是针对客户端要同时操作多个子系统时,可以在客户端和子系统之间建立一个外观类,这样客户端只需要操作外观类就可以了,用法实例比如多层架构中,上层通过接口对下层的进行调用, 该模式代码如下:
using System.Windows.Forms;
namespace DesignMode.Facade
{
//鱼
public class Fish
{
public void Swim()
{
MessageBox.Show("Start Swimming;");
}
}
//人
public class Person
{
public void Walk()
{
MessageBox.Show("Start Walking;");
}
}
//鸟
public class Bird
{
public void Fly()
{
MessageBox.Show("Start Flying");
}
}
//外观类
public class MyFacade
{
Fish fish;
Person person;
Bird bird;
public MyFacade()
{
fish = new Fish();
person = new Person();
bird = new Bird();
}
//全部比赛
public void Run_All()
{
fish.Swim();
person.Walk();
bird.Fly();
}
//鱼和人比赛
public void Run_FishAndPerson()
{
fish.Swim();
person.Walk();
}
//鱼和鸟比赛
public void Run_FishAndBird()
{
fish.Swim();
bird.Fly();
}
}
}
客户端调用:
private void btn_Facade_Click(object sender, EventArgs e)
{
MyFacade facade = new MyFacade();
facade.Run_All();//全部开始比赛
facade.Run_FishAndPerson();//鱼和人比赛
facade.Run_FishAndBird();//鱼和鸟比赛
}