Simple Factory mode (Introduction to design mode)

Source: Internet
Author: User

Before you learn a formal design pattern, start with an appetizer, the simple factory model. The following will design a calculator applet using the Simple factory model:

First, the operational base class (operation)

1      Public Abstract classOperation2     {3          Public DoubleNumA {Set;Get; }4          Public DoubleNumB {Set;Get; }5          Public Virtual DoubleGetResult ()6         {7             return 0;8         }9}

Second, the method of operation (+,-)

1      Public classoperationadd:operation2     {3          Public Override DoubleGetResult ()4         {5             Doubleres =0;6res =Base. NumA +Base. NumB;7             returnRes;8         }9     }Ten  One      Public classoperationsub:operation A     { -          Public Override DoubleGetResult () -         { the             Doubleres =0; -res =Base. NumA-Base. NumB; -             returnRes; -         } +}

Iii. Object Creation Classes

1      Public classoperationfactory2     {3          PublicOperation CreateOperation (stringop)4         {5Operation res =NULL;6             Switch(OP)7             {8                  Case "+":9res =NewOperationadd ();Ten                      Break; One                  Case "-": Ares =Newoperationsub (); -                      Break; -             } the             returnRes; -         } -}

Iv. implementation

1     /// <summary>2     ///Simple Factory mode-place the selection of the instance in the factory class3     /// </summary>4      Public classDosimplefactory:designpattern5     {6          Public Override voidExefun ()7         {8Console.WriteLine ("Please enter operator: + 、-、 *,/");9Operation OT =Newoperationfactory (). CreateOperation (Console.ReadLine ());TenOt. NumA =2; OneOt. NumB =4; A             Doubleres =ot. GetResult (); -Console.Write (string. Format ("The result is: {0}", Res)); -         } the}

Simple Factory mode (Introduction to design mode)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.