תבנית Command

בהנדסת תוכנה, תבנית Command, כפי שנובע משמה, היא תבנית שמייצגת פקודות. היא נועדה לעטוף (או להסתיר) את כל המידע הרלוונטי להרצת מתודה מסוימת (המופע ממנו קוראים לה, שמה, והפרמטרים שנשלחים לה) בתוך אובייקט יחיד. התבנית שימושית במימוש של תפריטים, ביצירת Progress Bar, בתבנית Thread Pools ועוד.

מבנה

מימוש

במימוש התבנית ארבעה מרכיבים עיקריים:

  • Command - ממשק המכיל בדרך כלל מתודה אחת - execute.
  • ConcreteCommand - מחלקה אשר מממשת את הממשק. בדרך כלל ניצור הרבה מחלקות כאלה - אחת לכל פקודה.
  • Invoker - תפקידה לבצע את הקריאה למתודה execute של ה-ConcreteCommand הנבחר. לעיתים תכיל טבלה של כל המימושים הקיימים לCommand ותקבל רק מספר או שם שמייצגים את המימוש הרצוי (לצורך יעילות).
  • Receiver - המחלקה עליה בעצם מבוצעת הפקודה.

דוגמאות מימוש

Java

/*the Command interface*/

public interface Command{
    void execute();
}

/*the Invoker class*/
public class Switch {

    private Command flipUpCommand;
    private Command flipDownCommand;

    public Switch(Command flipUpCmd,Command flipDownCmd){
         this.flipUpCommand=flipUpCmd;
         this.flipDownCommand=flipDownCmd;
    }

    public void flipUp(){
         flipUpCommand.execute();
    }

    public void flipDown(){
         flipDownCommand.execute();
    }

}

/*Receiver class*/

public class Light{

     public Light(){  }

     public void turnOn(){
        System.out.println("The light is on");
     }

     public void turnOff(){
        System.out.println("The light is off");
     }

}

/*the Command for turning on the light - ConcreteCommand #1*/

public class FlipUpCommand implements Command{

   private Light theLight;

   public FlipUpCommand(Light light){
        this.theLight=light;
       }

   public void execute(){
      theLight.turnOn();
   }

}

/*the Command for turning off the light - ConcreteCommand #2*/

public class FlipDownCommand implements Command{

   private Light theLight;

   public FlipDownCommand(Light light){
        this.theLight=light;
       }

   public void execute(){
      theLight.turnOff();
   }

}

/*The test class or client*/
public class PressSwitch{

   public static void main(String[] args){
       Light lamp = new Light();
       Command switchUp=new FlipUpCommand(lamp );
       Command switchDown=new FlipDownCommand(lamp );

       Switch s=new Switch(switchUp,switchDown);

       try {
           if (args[0].equalsIgnoreCase("ON")){
                s.flipUp();
                System.exit(0);
           }
           if (args[0].equalsIgnoreCase("OFF")){
               s.flipDown();
               System.exit(0);
           }
           System.out.println("Argument \"ON\" or \"OFF\" is required.");
           } catch (Exception e){
            System.out.println("Argument's required.");
           }

   }
}

C#

using System;

//the Command Interface
public interface ICommand
{
	void Execute();
}

//The ConcreteCommands
public class DVDPlayCommand : ICommand
{
	public DVDPlayCommand(){}
	public void Execute()
	{
		Console.WriteLine("DVD Started.");
	}
}

public class DVDStopCommand : ICommand
{
	public DVDStopCommand(){}
	public void Execute()
	{
		Console.WriteLine("DVD Stopped.");
	}
}

public class VCRPlayCommand : ICommand
{
	public VCRPlayCommand(){}
	public void Execute()
	{
		Console.WriteLine("VCR Started.");
	}
}

public class VCRStopCommand : ICommand
{
	public VCRStopCommand(){}
	public void Execute()
	{
		Console.WriteLine("VCR Stopped.");
	}
}

//The Invoker
public class Remote
{
	public Remote(){}
	public void Invoke(ICommand cmd )
	{
		Console.WriteLine("Invoking.......");
		cmd.Execute();
	}
}

//The Client
public class Client
{
	public Client(){}
	public static int Main(String[] args)
	{
		//Instantiate the invoker object
		Remote remote = new Remote();
		//Instantiate DVD related commands and pass them to invoker object
		DVDPlayCommand dvdPlayCommand = new DVDPlayCommand();
		remote.Invoke(dvdPlayCommand);
		DVDStopCommand dvdStopCommand = new DVDStopCommand();
		remote.Invoke(dvdStopCommand);
		//Instantiate VCR related commands and pass them to invoker object
		VCRPlayCommand vcrPlayCommand = new VCRPlayCommand();
		remote.Invoke(vcrPlayCommand);
		VCRStopCommand vcrStopCommand = new VCRStopCommand();
		remote.Invoke(vcrStopCommand);
		return 0;
	}
}

שימושים ידועים

  • שחזור (undo) - אם כל הפקודות של מערכת מסוימת יוחזקו כאובייקטים של Command אז התוכנית יכולה להחזיק מחסנית של כל הפקודות, ובביצוע undo להריץ את המתודה undo של הפקודה שבראש המחסנית (אותה שיטה יכולה להיות שימושית אפילו יותר אם מממשים טרנזקציות).
  • תפריטים ו-GUI - במימוש של תפריט, כל פעולה ניתנת למימוש על ידי command, מה שמקל על המימוש והסדר בו ניגשים לדברים.
  • Thread pools - התור של הפעולות שיש לבצע יכול להיות ממומש על ידי אובייקטים של Commands, והתהליכים פשוט יבצעו execute.

מקורות

קישורים חיצוניים

ויקישיתוף מדיה וקבצים בנושא תבנית Command בוויקישיתוף

Read other articles:

Nom officiel Централный Аерогидродинамический Институт, ЦАГИ Nom en français TsAGI Pays Russie Siège social Joukovski Création 1er décembre 1918 Effectif 3 700 Directeur général Boris S. Alyoshin Site Internet http://www.tsagi.com/ modifier  TsAGI, à gauche - Soufflerie subsonique T-105 TsAGI est l'acronyme russe de Institut central d'aérohydrodynamique (Централный Аерогидродинамический Институт, �...

 

 

Town in Kelantan, Malaysia This article is about the town. For the state constituency, see Dabong (state constituency). Dabong District Council Majlis Daerah Dabongمجليس دايره دابوڠTypeTypeLocal authority HistoryFounded1 January 1979LeadershipPresidentMohd Hariff Ghazali District secretaryMohd Fadzil Adnan Abdul Aziz MottoIkhlas Terus Maju(Sincere, Ever Onward)Meeting place18200 Dabong, Kelantan Darul Naim.Websitemddabong.kelantan.gov.my Dabong (Jawi: دابوڠ), also known as...

 

 

National anthem of Uruguay Himno Nacional de UruguayEnglish: National Anthem of UruguayNational anthem of  UruguayAlso known asOrientales, la Patria o la Tumba (English: Easterners, the Fatherland or the grave)LyricsFrancisco Acuña de Figueroa, 1833MusicFrancisco José Debali, 1845Adopted1848Audio sampleU.S. Navy Band instrumental versionfilehelp U.S. Navy Band instrumental version (short) U.S. Navy Band instrumental version (short with intro) 1930s orchestral and vocal rendit...

Railway signalling system This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Centralized traffic control – news · newspapers · books · scholar · JSTOR (December 2018) (Learn how and when to remove this message) The examples and perspective in this article deal primarily with the English-speaking world and do no...

 

 

 本表是動態列表,或許永遠不會完結。歡迎您參考可靠來源來查漏補缺。 潛伏於中華民國國軍中的中共間諜列表收錄根據公開資料來源,曾潛伏於中華民國國軍、被中國共產黨聲稱或承認,或者遭中華民國政府調查審判,為中華人民共和國和中國人民解放軍進行間諜行為的人物。以下列表以現今可查知時間為準,正確的間諜活動或洩漏機密時間可能早於或晚於以下所歸�...

 

 

Jan Adriaensens Nazionalità  Belgio Ciclismo Specialità Strada Termine carriera 1961 CarrieraSquadre di club 1952 Libertas1953 Libertas Rochet1954 LibertasL'ExpressAlpa1955 Terrot Libertas1956 Mercier1957-1958 Carpano1959 Peugeot1960 Philco1961 Groene LeeuwNazionale 1953-1961 Belgio   Modifica dati su Wikidata · Manuale Jan Adriaensens (Willebroek, 6 giugno 1932 – 2 ottobre 2018) è stato un ciclista su strada belga. ...

Cet article est une ébauche concernant la Colombie-Britannique. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Greenwood Administration Pays Canada Province Colombie-Britannique Subdivision régionale Kootenay Boundary Statut municipal cité (city) Maire Colleen Lang Constitution 1897 Démographie Population 665 hab. (2016) Densité 264 hab./km2 Géographie Coordonnées 49° 05′ 28″...

 

 

Large computer Mainframe redirects here. For other uses, see Mainframe (disambiguation). A single-frame IBM z15 mainframe. Larger capacity models can have up to four total frames. This model has blue accents, as compared with the LinuxONE III model with orange highlights. A pair of IBM mainframes. On the left is the IBM z Systems z13. On the right is the IBM LinuxONE Rockhopper. An IBM System z9 mainframe A mainframe computer, informally called a mainframe or big iron,[1] is a compute...

 

 

Alfred Russel Wallace Alfred Russel Wallace (Llanbadoc, 8 gennaio 1823 – Broadstone, 7 novembre 1913) è stato un naturalista, geografo, biologo, esploratore e antropologo britannico. Formulò la teoria dell'evoluzione assieme a Charles Darwin.[1] Indice 1 Vita e scoperte 1.1 Spedizione in Amazzonia 1.2 Spedizione nell'arcipelago malese 1.3 La selezione naturale e i rapporti con Darwin 1.4 La Linea di Wallace 1.5 Attivismo sociale 2 Opere 3 Onorificenze 4 Note 5 Bibliografia 6 Voci ...

Soviet llustrated magazine (1925–1941) Bezbozhnik (Безбожник)Cover of the magazine «Bezbozhnik» 1930, No. 19. A kulak with a barrel organ is depicted, in front of him is a peasant woman kneeling. On the barrel organ is a priest in the image of a parrot with a note that says: «Letter from the Holy Virgin. I, the Virgin, say: do not go to kolkhoz of the Bolsheviks».EditorY. M. Yaroslavsky, F. M. PutintsevCategoriesantireligiousFrequencyMonthlyFoundedMarch, 1925Final issueJune, 19...

 

 

African Union's space organisation African Space AgencyAgency overviewFormed24 January 2023; 16 months ago (2023-01-24)TypeSpace agencyJurisdictionAfrican UnionStatusActiveHeadquartersNew Cairo, Egypt Politics of the African Union Institutions Casablanca Group Union of African States Organisation of African Unity African Economic Community African Unification Front Executive Assembly Chairperson Commission Chairperson Conference and Events Peace & Sec. Pol. Affairs Infra...

 

 

For the infantry regiment, see Régiment de La Fère. Régiment de La Fère1ére Régiment d'Artillerie à Pied1ére Régiment d'ArtillerieInsignia of the 1st Artillery RegimentActive1671–PresentCountry FranceBranchFrench ArmyTypeArtilleryPart of1st DivisionGarrison/HQBelfortMotto(s)Royal d'abord premier toujoursConflicts War of the Austrian Succession Seven Years' War War of the First Coalition War of the Second Coalition Egyptian Campaign War of the Third Coalition War of the Fo...

هذه قائمة حلقات مسلسل ماجيك كايتو 1412، وهي السلسلة الثانية من سلسلة أنيمي ماجيك كايتو، والمسماة باسم ماجِك كايتو 1412 (まじっく快斗1412، Majikku Kaitō 1412؟) كان من إنتاج إستديو أيه-1 بكتشرز وبدأ عرضه في 4 أكتوبر 2014.[1] في بعض العناوين تُستخدم كلمات إنگليزية كما هي بحروف عربية؛ سبب ا...

 

 

Brad MehldauLahir(1970-08-23)23 Agustus 1970 Jacksonville, Florida, Amerika SerikatPekerjaanPemusik Jazz Brad Mehldau (lahir 23 Agustus 1970) adalah seorang pianis jazz asal Amerika Serikat. Ia telah banyak tampil dengan musisi-musisi jazz kelas satu Amerika seperti; Pat Metheny, Michael Brecker, Wayne Shorter, Christian McBride, Larry Grenadier, Peter Bernstein, Jeff Ballard, Joshua Redman, Chris Potter, Kurt Rosenwinkel, Brian Blade, Jimmy Cobb dan masih banyak lagi. Ia termasuk dari salah...

 

 

This article's tone or style may not reflect the encyclopedic tone used on Wikipedia. See Wikipedia's guide to writing better articles for suggestions. (January 2018) (Learn how and when to remove this message) American TV series or program New Wave TheatreCover of The Best of David Jove's New Wave Theatre, Volume 2GenreVariety, musicWritten byDavid Jove, Ed OchsDirected byDavid JovePresented byPeter IversOpening themeAmerican Music by The BlastersCountry of originUnited StatesOriginal langua...

فيلا سبيلامعلومات عامةالمكان Vela Luka (en) البلد  كرواتيا الإحداثيات 42°58′11″N 16°43′06″E / 42.969732°N 16.718357°E / 42.969732; 16.718357[1] الطول 40 متر المستوى 130 متر الاكتشاف 1835 الجيولوجيا كورتشولا تعديل - تعديل مصدري - تعديل ويكي بيانات يقع كهف فيلا سبيلا (بالكرواتية: Vela Spila ،Big Cave)...

 

 

百万新娘之爱无悔Noble Bride: Regretless Love别名百万新娘2类型都市情感剧/倫理溫馨和家族情仇编剧简远信导演王伟延主演李宗翰、张咏棋、张明明、张宝雯、张 亮、李 琳、李进荣、夏台凤、张 迪、唐艺昕、涂黎曼、馨 子国家/地区 中国语言汉语普通话集数72集片头曲爱无悔 (贾卿卿)片尾曲爱的迷雾 (贾卿卿、邬拉)制作制作人简远信拍攝地點 中国制作公司华策影...

 

 

Kepala Torquato Tasso di profil Bumban dafnah adalah sebuah rangkaian melingkar yang terbuat dari cabang atau daun Laurus nobilis atau pohon dafnah, sebuah tumbuhan hijau abadi aromatik, atau belakangan juga ada yang dibuat dari Ruscus hypoglossum atau Prunus laurocerasus. Dalam mitologi Yunani, Apollo digambarkan mengenakan sebuah bumban dafnah di kepalanya.[1] Maka dari itu, bumban dafnah dianggap sebagai simbol kemenangan. Referensi ^ Paulson, Ronald; Eisenman, Peter (2007). Sin an...

American music-oriented television show For the British program of the same name, see 120 Minutes (British TV programme). 120 MinutesCreated byDave KendallPresented byKevin Seal (1986-1987)Dave Kendall (1988–1992)Lewis Largent (1992–1995)Matt Pinfield (1995–1999, 2011–2013)Jim Shearer (2002–2003)Country of originUnited StatesNo. of seasonsOriginal: 17Revival: 1No. of episodesOriginal: approx. 839[1]Revival: 15 (aired)ProductionRunning time120 minutes (80–90 without commerc...

 

 

Stretch of Las Vegas Boulevard with many resorts, shows, and casinos Vegas Strip and The Strip redirect here. For other uses, see The Strip (disambiguation). Las Vegas StripThe StripLas Vegas Boulevard South Clockwise from top: Las Vegas Boulevard, MGM Grand Las Vegas, New York-New York, The Venetian Las Vegas, Caesars Palace, Horseshoe Las Vegas & Paris Las Vegas, BellagioLength4.2 mi (6.8 km)Coordinates36°07′11″N 115°10′21″W / 36.119684°N 115.172599�...