Essence:
Factory mode is to frame the creation of objects to the factory class, reducing the coupling between objects.
Usage examples:
1, simple factory---also called static factory
The essence of this is static: When a new object needs to be created, it can only be created by invoking the static method directly, without the factory class and the target object being created. This also forms the reorganization and optimization of the original creation logic.
Public InterfaceIService {BOOLSummit (); } Public classNormalorderservice:iservice { Public BOOLSummit () {//TODO Summit the normal order return false; } } Public classApplyorderservice:iservice {voidCreateorder (); Public BOOLSummit () {createorder (); //TODO Summit the Apply order return false; } } Public classBookorderservice:iservice {BOOLcheckdate (DateTime time); Public BOOLSummit () {if(Checkdate (DateTime.Now)) {//TODO Summit the Bookorder return true; } Else { return false; } } } Public classServicefactory { Public StaticIService CreateService (stringOrderType) { Switch(ordertype) { Case "Normal": return NewNormalorderservice (); Case "Apply": return NewApplyorderservice (); Case " Book": return NewBookorderservice (); default: return NULL; } } }
Call Servicefactory.createservice () directly when called. Summit () to create a factory or instance object that does not need to be displayed when the business is implemented.
The disadvantage is that when a new service is added, the factory class needs to be changed, which is equivalent to affecting the existing code, and does not conform to the open and closed principle.
My view on the factory model