Reprint Please specify source: http://blog.csdn.net/lhy_ycu/article/details/39784403
Abstract Factory: Abstract Factory-As the name implies, the factory is abstracted out, different factories produce different products. This is a good thing: once you need to add new functionality, add the new factory class directly, and you don't need to modify the previous code.
First, UML modeling diagram:
Second, the code implementation
/** * Example: Abstract factory-As the name implies, is to abstract the factory, different factories produce different products * * Advantages: Once you need to add new functions, directly add new factory class on it, do not need to modify the previous code */interface Sender {public void send ();} Class Emailsender implements Sender {@Overridepublic void Send () {System.out.println ("This is a email ...");}} Class Smssender implements Sender {@Overridepublic void Send () {System.out.println ("This is a SMS ...");}} /** * Role: Abstract Factory */interface abstractfactory {public Sender produce ();} /** * Mail Factory */class Emailsendfactory implements Abstractfactory {@Overridepublic Sender produce () {return new Emailsender () ;}} /** * SMS Factory */class Smssendfactory implements Abstractfactory {@Overridepublic Sender produce () {return new Smssender ();}} /** * Client Test class * * @author Leo */public class Test {public static void main (string[] args) {/** * Create factory */abstractfactory Factory = new Smssendfactory ();/** * Production product */sender Sender = Factory.produce ();/** * Execute business logic */sender.send ();}}
Iii. Summary
If you want to add a feature now: to give special attention to a friend to send messages, you just need to do an implementation class, to implement the sender interface, while doing a factory class, implement the Abstractfactory interface, you can, without modifying the existing code. This is a better way to expand!
Java Design Pattern Rookie series (v) Modeling and implementation of abstract factory model