Factory method (factorymethod ):
Defines an interface for creating objects, so that the subclass determines which class to instantiate. Factory method delays the instantiation of a class to its subclass.
The factory method mode effectively solves the problem of poor scalability in the simple factory mode. To expand the mode, you only need to add a new class without changing the original class. The following is an example:
Public interface person {
}
Public class student implements person {
}
Public class teacher implements person {
}
Public interface personfactory {
Public Person produceperson ();
}
Public class studentfactory implements personfactory {
@ Override
Public Person produceperson (){
Return new student ();
}
}
Public class teacherfactory implements personfactory {
@ Override
Public Person produceperson (){
Return new teacher ();
}
}
Public class test {
Public static void main (string [] ARGs ){
Personfactory PF;
Person P;
PF = new studentfactory ();
P = PF. produceperson ();
// P is the student object.
PF = new teacherfactory ();
P = PF. produceperson ();
// P is the instructor's mobile phone.
}
To produce farmer, you only need to add a new farmer class to implement the person interface, and then add a new farmerfactory to implement the personfactory interface. The newly added code is as follows:
Public class farmer implements person {
}
Public class farmerfactory implements personfactory {
@ Override
Public Person produceperson (){
Return New Farmer ();
}
}
In this way, a new product of this factory is added, but the requirements of the original class will not be changed. However, this still causes problems. In the factory method mode, what is actually produced is written into the code (we call it hard code). What if the consumer wants student this time and wants hunter next time, it is impossible for us to change the code once when we raise a requirement. This obviously does not work. Therefore, the abstract factory mode is available below to solve this problem-to be continued