Factory mode, as the name implies, is to use a factory to produce a series of identical objects, where the same object refers to the implementation of the same interface or inherit the uniform parent class object.
If you only need to create one or two objects, then simply new one object, if you need to create a large number of objects, and these objects are all implemented an interface, then using Factory mode to create objects is more elegant.
The various explanations of the factory model are not much to say, here wrote a small demo simple implementation of this idea.
The factory model is divided into factory methods and abstract factory models, the latter I still do not understand, and so on later on the day to understand the record. Fortunately, the factory method model is used more.
Small Demo
Create an interface:
1 Public Interface Sender {2 /** 3 * Send interface 4 */ 5 void send (); 6 }
There are two implementation classes that implement the interface, sending messages and text messages separately
1 public class MailSender implements Sender { 2 @Override 3
public
void
send ( {
4 System.out.println ("Mailsender.send () ..."
5
}
6 }
1 Public class Implements Sender {2 @Override3public void send () { 4 System.out.println ("Smssender.send () ..."); 5 }6 }
When I want to create a lot of mailsender and smssender, I need to constantly new to new, which is that we need a sending factory, you tell me what I send what, to achieve more elegant.
1 Public classSenderfactory {2 3 Public StaticSender Createsender (class<?extendsSender>Senderclass)4 {5 Try {6Sender sender = Senderclass.newinstance ();//Reflection Get Instance7 returnSender;8}Catch(instantiationexception e) {9 e.printstacktrace ();Ten}Catch(illegalaccessexception e) { One e.printstacktrace (); A } - return NULL; - } the}
Test:
1 Public classTest {2 Public Static voidMain (string[] args) {3Sender sender = Senderfactory.createsender (MailSender.class);4 sender.send ();5Sender = Senderfactory.createsender (smssender.class);6 sender.send ();7 }8}
Output:
Very good hehe hehe.
The Factory mode of Java design mode