Understanding : The "Extract factory class" In this article refers to the complexity of the code if you are creating many objects. A good way to do this is to extract the factory class.
In general, we need to set up some objects in our code in order to get their state, so that we can use objects, so-called settings are often the way to create an instance of an object and invoke an object. Sometimes the code becomes complex if you want to create a lot of objects. This is where the factory model works. The complex application of Factory mode is to create an object set using an abstract factory, but here we are simply using the basic factory class to create a simple application of the object.
Refactoring Pre-code:
1 Public classPolicecarcontroller2 { 3 PublicPolicecar New (intMileage,BOOLservicerequired)4 { 5Policecar Policecar =NewPolicecar ();6policecar.servicerequired =servicerequired;7Policecar.mileage =mileage;8 9 returnPolicecar;Ten } One}
The new method contains the entire logic for creating the class, and if you are creating more analogies and more complex logic (such as creating objects based on different conditions, when creating objects), our new method logic becomes large and the code becomes difficult to maintain. So we're going to use the extraction plant class to refine it.
Post-Refactoring code:
1 Public Interfaceipolicecarfactory2 {3Policecar Create (intMileage,BOOLservicerequired);4 }5 6 Public classpolicecarfactory:ipolicecarfactory7 {8 PublicPolicecar Create (intMileage,BOOLservicerequired)9 {TenPolicecar Policecar =NewPolicecar (); OnePolicecar.readforservice =servicerequired; APolicecar.mileage =mileage; - returnPolicecar; - } the } - - Public classPolicecarcontroller - { + PublicIpolicecarfactory Policecarfactory {Get;Set; } - + PublicPolicecarcontroller (ipolicecarfactory policecarfactory) A { atPolicecarfactory =policecarfactory; - } - - PublicPolicecar New (intMileage,BOOLservicerequired) - { - returnpolicecarfactory.create (mileage, servicerequired); in } -}
The new method becomes very simple, which means that the call to implementIpolicecarfactoryinterface ofpolicecarfactory
If the object to be created is one, you can use a simple factory, but there are still a lot of dependencies and it's not easy to maintain. It is recommended to use the factory method pattern to defer instantiation to subclasses. If you want to create a series of objects, it is recommended that you use the abstract Factory mode, but be careful not to over-design, as long as you can meet the changing needs and for the future maintenance and refactoring to bring convenience.
Refactoring 19th Day Extract factory class (Extract Factory classes)