统一求存(Facade)

类别:.NET开发 点击:0 评论:0 推荐:

 

感觉有点政治的味道.当然.我们并不讨论政治.只是在说明很多情况下都必须进行的一种措施

事实上.当你并不想为每一个子系统建立独立的操作的时候.你也许更加希望能够有一个单一

的操作方案可供选择.那要不必为每个子系统都寻求其特有的操作方案.使操作变的单一.Facde

就可以做到这一点.

假设你有三个播音设备.分别使CD 磁带机,Mp3 它们分别有自己独立的操作放案.这让你很头痛

因为你必须掌握三套类似却有相对独立的方案.那么我们考虑如何解决

class CDPlay{
 private  string SongName;
 CDPlay(string sn){
  SongName=sn;
 }

 public void PlayCd(){
    Console.WriteLine("Play Cd" + SongName);
 }
 
 public void StopCd(){
  Console.WriteLine("Stop Cd");
 }

}

class RecordPlay{
 private  string SongName;
 RecordPlay(string sn){
  SongName=sn;
 }

 public void PlayRecord(){
    Console.WriteLine("Play Record" + SongName);
 }
 
 public void StopRecordd(){
  Console.WriteLine("Stop Record");
 }
}

class Mp3Play{
 private  string SongName;
 CDPlay(string sn){
  SongName=sn;
 }

 public void PlayMp3(){
    Console.WriteLine("Play Mp3" + SongName);
 }
 
 public void StopMp3(){
  Console.WriteLine("Stop Mp3");
 }
}

 

//下面我们建立统一的界面

class Facade {
 private Mp3Play mp3;
 private RecordPlay rp;
 private CDPlay cd;
 
 private string playName;
 private  string songName;

 public string PlayName{
  get{return playName;};
  set{playName=value;};
 }
 
 public string SongName{
  get{return SongName;};
  set{SongName=value;};
 }

 public Facade(string pn,string sn){
   playName=pn;
   songName=sn;
 }
 
 public void play(){
   switch(playName){
     case "CD":
     Cd=new CDPlay(songName);
     Cd.PlayCd();
    case "mp3":
     mp3=new Mp3Play(songName);
     mp3.PlayMp3();
    case "Record":
     rd=new RecordPlay(songName);
     rd.PlayRecord();
   }
 }
 
 public void stop(){
    case "CD":
     Cd=new CDPlay(songName);
     Cd.stopCd();
    case "mp3":
     mp3=new Mp3Play(songName);
     mp3.stopMp3();
    case "Record":
     rd=new RecordPlay(songName);
     rd.stopRecord();
 }
}


//调用

public class Client
    {
       public static int Main(string[] args)
  {
   Facade facade = new Facade("CD");
   facade.play();
                        facade.Stop();

                        facade.PlayName="mp3";
                        facade.play();
                        facade.Stop();

                        facade.PlayName="Record";
                        facade.play();
                        facade.Stop();
            return 0;
        }
    }

这样我们只需要一个统一的界面.而不需要知道其每个子系统是如何特别定制的.

本文地址:http://com.8s8s.com/it/it45527.htm