Reprint Please specify source: http://blog.csdn.net/lhy_ycu/article/details/39856435
Builder mode: The factory class pattern provides a pattern for creating a single class, while the builder pattern is to centralize the various products for management. For the sake of simplicity, you can get the builder mode by modifying the previous factory method pattern.
First, UML modeling:
Second, the Code implementation
/** * Example: Builder mode * * differs from Factory mode: The factory class mode provides the creation of a single class, while the builder pattern is to centralize various products for management */interface Sender {public void Send ();} Class Emailsender implements sender {@Overridepublic void send () {System.out.println ("Send with e-mail ...");}} Class Smssender implements sender {@Overridepublic void send () {System.out.println ("Send with SMS ...");}} Class Builder {private list<sender> List = new arraylist<sender> ();p ublic list<sender> getList () { return list;} public void Produceemailsender (int. count) {for (int i = 0; i < count; i++) {List.add (New Emailsender ());}} public void Producesmssender (int. count) {for (int i = 0; i < count; i++) {List.add (New Smssender ());}}} /** * Client Test class * * @author Leo */public class Test {public static void main (string[] args) {Builder builder = new Builder () ; Builder.produceemailsender (5); Builder.producesmssender (5);/** * Iterates through the elements in list */list<sender> list = Builder.getlist (); for (int i = 0; i < list.size (); i++) {Sender sender = List.get (i); System.out.println (sender); sender.send ();}}}
Iii. Summary
The builder pattern integrates many functions into a class that can create more complex things. So the difference with the factory model is that the factory model is concerned with creating a single product, while the builder pattern is concerned with creating multiple objects and parts.
Java Design Patterns Rookie series (15) Builder Model Modeling and implementation