Java Design Pattern cainiao series (v) abstract factory pattern modeling and implementation

Source: Internet
Author: User

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!

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.