1. Introduction of factory method pattern

One problem with the simple factory model is that the creation of classes depends on the factory class, which means that if you want to extend the program, you have to modify the factory class. This violates the closure principle. So, from a design point of view, there are some problems. Using the factory method pattern, create a factory interface and create multiple factory implementation classes so that whenever you need to add new functionality, you can simply add new factory classes without modifying the previous code.Copy the code

2. Implementation of factory method pattern

Public interface Sender {public void Send(); public void Send(); } (2) Secondly, Public class MailSender implements Sender {@override public void Send() {system.out.println ("this is mailsender!" ); } } public class SmsSender implements Sender { @Override public void Send() { System.out.println("this is sms sender!" ); }} (3) create two factory classes:  public class SendMailFactory implements Provider { @Override public Sender produce(){ return new MailSender(); } } public class SendSmsFactory implements Provider{ @Override public Sender produce() { return new SmsSender(); }} Public interface Provider {public Sender produce(); } best ignored: It is worth noting that the above two factory classes do not have only one create method when it comes to the abstract factory class; they represent a class of create method clusters with common attribute values. Public class Test {public static void main(String[] args) {Provider Provider = new SendMailFactory(); Sender sender = provider.produce(); sender.Send(); }} this is SMS sender!Copy the code

3 summary

The nice thing about this pattern is that if you now want to add a function that sends instant messages, you just have to create an implementation class that implements the Sender interface, and a factory class that implements the Provider interface, and you're fine, you don't have to change the existing code. This way, the expansion is better!Copy the code