23 Design Modes: Factory method mode

Source: Internet
Author: User

The factory method pattern is to put the factory class into a method to create, so that the factory class can be created, but also do not modify the factory class code, so as to extend the functionality, the other advantage of the design is that the code is well encapsulated.

Cases:

Create a factory interface

public interface sender{

public void Send ();

}

Two factory implementation classes

public class MailSender implements sender{

@Override

public void Send () {

System.out.println ("This is mainsender!");

}

}

public class Smssender implements sender{

@Override

public void Send () {

System.out.println ("This is smssender!");

}

}

The interface of the class used to create the factory class

public interface provider{

Public Sender produce ();

}

Create two implementation classes

public class Mailclass implements provider{

@Override

Public Sender Produce () {

return new MailSender ();

}

}

public class Smsclass implements provider{

@Override

Public Sender Produce () {

return new Smssender ();

}

}

Test class

public class sendertest{

public static void Main () {

Provider Provider = new Smsclass ();

Sender Smssender = Provider.produce ();

Smssender.send ();

}

}

23 Design Modes: Factory method mode

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.