The problem with factory method mode is that class creation relies on the factory class, that is, if you want to expand the program, the factory class must be modified, which violates the closure principle, so from the design point of view, there are certain problems, how to solve? Use the abstract factory pattern to create multiple factory classes so that once you need to add new functionality, you can add new factory classes directly, without having to modify the previous code.
A unified parent interface for the factory class that can be used to extend
Because the abstract factory is not very good to understand, first look at the diagram, and then the code, it is more easily understood.
Example:
Public Interface Sender { publicvoid Send (); }
Two implementation classes
Public class Implements Sender { @Override publicvoid Send () { System.out.println ("This is mailsender! " ); } }
Public class Implements Sender { @Override publicvoid Send () { System.out.println ( "This is SMS sender!" ); } }
Provides a factory parent class interface:
Public Interface Provider { public Sender Produce (); }
Two factory classes:
Public class Implements Provider { @Override public Sender Produce () { return New MailSender (); } }
Public class Implements provider{ @Override public Sender Produce () { returnNew Smssender (); } }
Test class:
Public class Test { publicstaticvoid main (string[] args) { new sendmailfactory (); = provider.produce (); Sender. Send (); } }
In fact, the advantage of this model is that if you want to add a function now: Send timely information, you just need to do an implementation class, to implement the sender interface, at the same time do a factory class, implement Provider interface, OK, no need to change the ready-made code. To do so, expand better!
Java design mode-abstract Factory mode (Factory)