Design Pattern: Factory method Pattern (Factory mode)
Introduction: The Simple factory model is to make a decision in the factory class through the data, instantiate one of the classes in the factory class and do the operation. But the factory method pattern is one of his extensions, does not differentiate in the factory class to create the corresponding class, but the decision-making power of the decision to use the user class. Scalability is much better than simple Factory mode
Factory method Pattern Class diagram:
Simple Factory mode C # code example: Mobilephone class Mobile Phone class
1 Public Abstract class Mobilephone 2 {3public abstractvoid print (); 4 }
iphone type Apple phone class
1 Public class Iphone:mobilephone 2 {3public overridevoid print ()4 {5 Console.WriteLine (" I'm an apple phone! "); 6 }7 }
Xiaomi type Millet mobile phone class
1 Public class Xiaomi:mobilephone 2 {3public overridevoid print ()4 {5 Console.WriteLine (" I am a Xiaomi phone "); 6 }7 }
Smartisan Type Hammer Phone class
1 Public class Smartisan:mobilephone 2 {3public overridevoid print ()4 {5 Console.WriteLine (" I'm a hammer phone! "); 6 }7 }
Mobilephonefactory Type mobile phone factory class
1 Public Abstract class mobilephonefactory 2 {3public abstract mobilephone Create (); 4 }
Iphonefactory Type Apple phone factory
1 Public class iphonefactory:mobilephonefactory 2 {3public override mobilephone Create ()4 {5 returnnew Iphone (); 6 }7 }
xiaomifactory type Millet phone factory
1 Public class xiaomifactory:mobilephonefactory 2 {3public override mobilephone Create ()4 {5 returnnew Xiaomi (); 6 }7 }
smartisanfactory Type Hammer Phone factory class
1 Public class smartisanfactory:mobilephonefactory 2 {3public override mobilephone Create ()4 {5 returnnew Smartisan (); 6 }7 }
Test
(Even if you add a new brand every time, you only need to add a new brand of the class, and the corresponding factory can be used, easy to expand)
1 class Program2 {3 Static voidMain (string[] args)4 {5 //create an Apple phone factory6Mobilephonefactory Mobilephonefactoryiphone =Newiphonefactory ();7 //Apple phone Factory creates mobile phone8Mobilephone Mobilephoneiphone =mobilephonefactoryiphone.create ();9 //create an Apple phone from Apple factoryTen mobilephoneiphone.print (); One A - //Xiaomi Factory produces Xiaomi mobile phone -Mobilephonefactory Mobilephonefactoryxiaomi =Newxiaomifactory (); theMobilephone Mobilephonexiaomi =mobilephonefactoryxiaomi.create (); - mobilephonexiaomi.print (); - - + //Hammer Phone factory production hammer mobile phone -Mobilephonefactory Mobilephonefactorysmartisan =Newsmartisanfactory (); +Mobilephone Mobilephonesmartisan =mobilephonefactorysmartisan.create (); A mobilephonesmartisan.print (); at - Console.read (); - - } -}Operation Result:
SOURCE Engineering Files
C # Design Pattern-factory method mode