設計模式之Command——電視篇(原創)

來源:互聯網
上載者:User

設計模式之Command——電視篇

 

每天晚上,搶電視遙控器都是我們家的保留節目。女兒喜歡看卡通屏道,老婆喜歡看電視劇屏道,我呢則喜歡看足球屏道。因此誰控制了遙控器,就等於實現了自己的節目夢想了。嘿嘿,其實每次都是我女兒成功得到,而且她還每次都陣陣有詞的說:“大的應該讓小的嗎?”,你看這孩子,不知跟誰學的。然後遙控器就是老婆的,最後才輪到我,當我高興的按到足球屏道時,播音員說:“今天的節目就到這裡了,請明天在看!”,我倒地狂嘔血。

大家都知道電視遙控器節目面板(ProgramPan)是由節目按鈕組成,通過選擇相應的節目按鈕,就可以切換到相應的節目屏道。

下來讓我們看看如何?通過遙控器按鈕選擇節目屏道的過程吧。

 

1、在這裡,先定義遙控器按鈕(RemoteControlButton)介面:

public interface RemoteControlButton {

  public abstract void  selectProgram(); //選擇節目屏道

}

2、再定義遙控器按鈕(RemoteControlButton)介面的實作類別:

A:卡通節目按鈕(CartonProgramButton)類:

public class CartonProgramButton implements RemoteControlButton{

  public void selectProgram() {

    System.out.println("選擇了卡通屏道!");

  }

}

B:電視劇節目按鈕(TvPlanProgramButton)類:

public class TvPlanProgramButton implements RemoteControlButton {

  public void selectProgram() {

    System.out.println("選擇了電視劇屏道!");

  }

}

C:足球節目按鈕(FootProgramButton)類:

public class FootProgramButton implements RemoteControlButton {

  public void selectProgram() {

    System.out.println("選擇了足球屏道!");

  }

}

3、遙控器節目面板(ProgramPan)類:用來控制節目按鈕,顯示節目

public class ProgramPan {

  public static List programList() {

    List list = new ArrayList();  //節目屏道按鈕列表

    list.add(new CartonProgramButton()); //卡通屏道按鈕

    list.add(new TvPlanProgramButton()); //電視劇屏道按鈕

    list.add(new FootProgramButton());   //足球屏道按鈕

    return list;

  }

}

4、編寫測試類別:

public class TestCommand {

  public static void main(String[] args) {

    List list = ProgramPan.programList();  //獲得節目屏道按鈕

    for (Iterator it = list.iterator();it.hasNext();)

      ( (RemoteControlButton) it.next()).selectProgram();  //選擇節目屏道中對應的節目

  }

}

5、說明:

A:Command說白了就是通過選擇一個個命令,然後執行相應動作。

B:Command是對行為進行封裝的典型模式,在本例中通過遙控器節目面板(ProgramPan)這個封裝類來實現我們看電視節目的目的。

C:Command模式和Facade(外觀)模式似乎比較相似。都是通過封裝類來進行訪問的。如何區分,對這點我也比較疑惑。
   D:Command模式是用collection的對象容器類,把另一些類放到裡面,以實現集體的一塊操作,以進行封裝。facade模式是把某個功能的操作,集中放在一起,使之用一個統一的,對外介面,比如:封裝資料庫操作,發郵件操作等等。
   6、特此感謝:
   感謝changlich網友對Command模式和facade模式的區別的解釋,特此將這個解釋加入到說明中,希望能對大家有所協助。再次感謝大家的支援。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.