Simple Factory mode : A factory object determines which product class is created, and the Simple Factory mode is the simplest and most practical mode in the factory model family.
Purpose : Provides a transition interface for creating objects to isolate the specific process masks for creating objects for increased flexibility.
It consists of:
1) Factory class role: This is the core of this model, contains certain business logic and judgment logic. In Java it is often implemented by a specific class.
2) Abstract Product role: It is generally the product of the specific inheritance of the parent class or implementation of the interface. Implemented in Java by an interface or an abstract class.
3) Specific product roles: the object created by the factory class is an instance of this role. Implemented in Java by a concrete class.
An example of a factory producing televisions and mobile phones is to explain:
Define two classes to represent the TV and mobile phones, and implement the work interface.
1 Interfacework{2 Public voidworking ();3 }4 classPhoneImplementswork{5 6 @Override7 Public voidworking () {8System.out.println ("Production phone");9 }Ten One } A classTvImplementswork{ - - @Override the Public voidworking () { -System.out.println ("Production TV"); - } - +}
Then, if you want to use these two classes, you can use the normal method of creating objects
1 Public classTest10 {2 3 Public Static voidMain (string[] args) {4Phone phone=NewPhone ();5 phone.working ();6 7Tv tv=NewTv ();8 tv.working ();9 }Ten One}
The advantage of this is that, if the phone class and TV class change, you have to change the above code, you can say that class Test10 relies on the phone class and TV class, called this dependency as a coupling: The user directly uses the specific class, indicating that the current class depends on the specific class. So when this specific class changes, the user will be affected.
In order to reduce this effect, the Factory mode is introduced:
Add a factory class
1 classfactory{2 Public StaticWork Getwork (String product) {3 if("Phone". Equals (product)) {4 return NewPhone ();5}Else if("TV". Equals (product)) {6 return NewTv ();7 }8 return NULL;9 }Ten}
This way the code for the Test10 class can be:
1 Public classTest10 {2 3 Public Static voidMain (string[] args) {4 //Dependency Interface5Work Work=factory.getwork ("TV");6 if(work!=NULL){7 work.working ();8 }9 }Ten One}
Thus it transforms the dependence of a concrete class into a dependent interface, reduces the coupling, and embodies the idea of interface-oriented programming.
Such a change in the specific class does not affect it.
This code, although similar to the above results, is extensible and more maintainable.
———————————————————————— welcome all Bo Friends point out the shortcomings, a lot of exchanges.
Java mode-Simple Factory mode