Java Design Pattern cainiao series (v) abstract factory pattern modeling and implementation
Abstract Factory: Abstract Factory, as its name implies, abstracts factories to produce different products. This has the advantage: Once new functions need to be added, new factory classes can be added directly without modifying the previous code.
1. uml modeling Diagram:
Ii. Code Implementation
/*** Example: Abstract Factory -- as the name suggests, it is to abstract the factory to produce different products in different factories. ** advantages: Once new functions need to be added, you can simply add a new factory class without modifying 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 ();}/*** email 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 function: send messages to friends of special interest, you only need to create an implementation class to implement the Sender interface and a factory class to implement the AbstractFactory interface, you do not need to modify the existing code. The scalability is better!