The factory method pattern is to put the factory class into a method to create, so that the factory class can be created, but also do not modify the factory class code, so as to extend the functionality, the other advantage of the design is that the code is well encapsulated.
Cases:
Create a factory interface
public interface sender{
public void Send ();
}
Two factory implementation classes
public class MailSender implements sender{
@Override
public void Send () {
System.out.println ("This is mainsender!");
}
}
public class Smssender implements sender{
@Override
public void Send () {
System.out.println ("This is smssender!");
}
}
The interface of the class used to create the factory class
public interface provider{
Public Sender produce ();
}
Create two implementation classes
public class Mailclass implements provider{
@Override
Public Sender Produce () {
return new MailSender ();
}
}
public class Smsclass implements provider{
@Override
Public Sender Produce () {
return new Smssender ();
}
}
Test class
public class sendertest{
public static void Main () {
Provider Provider = new Smsclass ();
Sender Smssender = Provider.produce ();
Smssender.send ();
}
}
23 Design Modes: Factory method mode