Write in front, PS a sentence: notes dedicated, Pat do not spray, see the uncomfortable detour forward can.
I. Lifting INSTRUCTIONS
1. Plot: A bank finance has three employees, respectively, a, B, C three people, the main task is to go to the bank to withdraw money, as follows:
classEmloyeea: { Public voiddosomething () {Console.WriteLine ("EMLOYEEA to fetch the money."); } } classEmloyeeb { Public voiddosomething () {Console.WriteLine ("Emloyeeb to fetch the money."); } } classEMLOYEEC { Public voiddosomething () {Console.WriteLine ("EMLOYEEC to fetch the money."); } }
One day the director said: "A to get money" or "B to get money" when it is like the following action:
class Manager { public Manager () { new Emloyeea (); Emloyeea.dosomething (); New Emloyeea (); Emloyeeb.dosomething (); } }
Above, all actions have been completed, but so down to find code coupling high (direct contact for each employee), poor encapsulation (each employee information is exposed to the outside), but also useful for their own words is trouble, not easy to maintain later .
The following modifications are made to the Factory mode:
2. Create an Employee abstract class: Iemolyee, then each employee inherits from that class:
Public InterfaceIEmployee {voiddosomething (); } Public classEmloyeea:iemployee { Public voiddosomething () {Console.WriteLine ("EMLOYEEA to fetch the money."); } } classEmloyeeb:iemployee { Public voiddosomething () {Console.WriteLine ("Emloyeeb to fetch the money."); } } classEmloyeec:iemployee { Public voiddosomething () {Console.WriteLine ("EMLOYEEC to fetch the money."); } }}
3. Establishment of the plant:
Public Interfaceifactory {iemployee creat (stringID); } Public classFactory:ifactory { PublicIEmployee creat (stringID) {Switch(ID) { Case "A": return NewEmloyeea (); Case "B": return NewEmloyeeb (); Case "C": return NewEMLOYEEC (); default: return NewEmloyeea (); } } }
4. The supervisor invokes the employee:
New Factory (); = Factory. creat ("A"); = Factory. creat ("B"); Employeea.dosomething (); Employeeb.dosomething (); Console.ReadLine ();
The above is a simple example of Factory mode.
Two. Factory mode features
1. By Iemplyee, the dependence of supervisors and employees is isolated, the coupling is reduced and the Emplyeex information is not visible to the supervisor.
2. Even if the information and the overall staff of the increase, deletion, change operation does not affect the overall situation, the precise said the supervisor does not care about employee changes.
3 in terms of code operations, it is relatively straightforward to write a Emplyeex out and call the factory much more convenient.
Three. Sample code
Above.
The Factory mode of C # design mode (i)