表象模式 (Facade Pattern) ,是把好幾種類別物件的方法,封裝在一個表象類別的方法內,只需要執行表象類別的方法,就等於執行了封裝在內部多個物件的方法。
一個上班族可能有以下動作:
可以透過表象模式類別封裝,只要執行上班、休息、下班的動作就好。
public class Facade{
///<summary> 辦公室軟體 </summary>
protected class Office
{
public void Open()
{
Console.WriteLine("Office: New");
}
public void Save()
{
Console.WriteLine("Office: Save");
}
public void Close()
{
Console.WriteLine("Office: Close");
}
}
///<summary> 音樂播放器 </summary>
protected class AudioPlayer
{
public void Play()
{
Console.WriteLine("Player: Play");
}
public void Pause()
{
Console.WriteLine("Player: Pause");
}
public void Stop()
{
Console.WriteLine("Player: Stop");
}
}
///<summary> 表象模式: 工作組合 </summary>
protected class WorkSuiteFacade
{
protected Office office;
protected AudioPlayer player;
public WorkSuiteFacade()
{
office = new Office();
player = new AudioPlayer();
}
public void StartWork()
{
office.Open();
player.Play();
}
public void Break()
{
office.Save();
player.Pause();
}
public void StopWork()
{
office.Save();
office.Close();
player.Stop();
}
}
public void Run(){
WorkSuiteFacade workFacade = new WorkSuiteFacade();
Console.WriteLine("### Morning");
workFacade.StartWork();
workFacade.Break();
Console.WriteLine("### Afternoon");
workFacade.StartWork();
workFacade.StopWork();
}
}
執行結果:
### Morning
Office: New
Player: Play
Office: Save
Player: Pause
### Afternoon
Office: New
Player: Play
Office: Save
Office: Close
Player: Stop