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)