usingSystem;namespaceconsoleapplication7{classProgram {/// <summary> ///Template Method Pattern--Define an algorithm skeleton in an operation in an abstract class (corresponding to the template that everyone downloads in life),///instead, defer some steps to the subclass to implement it (which corresponds to what we populate the template with in our own case). ///The template method allows subclasses to redefine some specific steps of an algorithm without changing the structure of an algorithm,///The template method pattern moves the invariant behavior to the superclass, eliminating duplicate code in the subclass. /// </summary> /// <param name= "args" ></param> Static voidMain (string[] args) { //Create a Spinach instance and invoke the template methodSpinach Spinach =Newspinach (); Spinach. Cookvegetabel (); Console.WriteLine ("----------------------------------------------"); Chinesecabbage Chinesecabbage=NewChinesecabbage (); Chinesecabbage. Cookvegetabel (); Console.read (); } /// <summary> ///Vegetable Super Class/// </summary> Public Abstract classVegetabel {//template method, do not define the stencil method as the virtual or abstract method, avoid overwriting the quilt class, and prevent changing the order of execution of the process Public voidCookvegetabel () {Console.WriteLine ("the general practice of copying vegetables"); This. Pouroil (); This. Heatoil (); This. pourvegetable (); This. Stir_fry (); } //first step pour oil Public voidPouroil () {Console.WriteLine ("pour oil"); } //burn the oil hot Public voidHeatoil () {Console.WriteLine ("burn the oil hot"); } //when the oil is hot, the vegetables go down, and the specific vegetables are decided by the subclass. Public Abstract voidpourvegetable (); //development of stir-fried vegetables Public voidStir_fry () {Console.WriteLine ("Stir Fry"); } } //Spinach Public classSpinach:vegetabel { Public Override voidpourvegetable () {Console.WriteLine ("pour the spinach into the pot"); } } //Chinese Cabbage Public classChinesecabbage:vegetabel { Public Override voidpourvegetable () {Console.WriteLine ("pour the cabbage into the pot"); } } }}
14. Template Method Mode