Java- factory design pattern

                           Java factory design pattern 

I, on the factory design pattern

Description : Design mode to create schema belongs, it provides the best way to create objects. In Factory mode, we will not expose the client to create a logical when you create an object,

    And by using a common interface to point to the newly created object.

 

Intent: Defines a created object's interface, let subclasses decide which instance of a class factory, the factory model so that the process of creating the delay to subclasses.

Mainly to solve: the main problem of interface options.

When to use: When you create different instances in different conditions we definitely plan.

How to solve: let subclasses to implement the factory interface, it is an abstract of the returned product.

Category : General simple factory simple factory, plant more simple method, a plurality of static methods, factory design pattern.

 

Second, code implementation

  Simple Factory: is to create a factory class, to achieve the same interface classes created instance. First, look at the diagram

  

For example as follows :( We give an example of sending e-mail and SMS)

First, create common interfaces between the two:

Sender

Package pers.hupo.hupow.factory;
 / ** 
 * @author HUPO
 * Create an interface
 * */
public interface Sender {
    void Send();
}
View Code

Second, create an implementation class:

mail Sender

Package Penalty for pers.hupo.hupow.factory;

/ ** 
 * @author HUPO
 * Sender implementation class
 * */
public class MailSender implements Sender {
    @Override
    public void Send() {
        System.out.println("this mail message");
    }
}
View Code

SmsSender

Package Penalty for pers.hupo.hupow.factory;

/ ** 
 * @author HUPO
 * Sender implementation class
 * * / 
Public  class SmsSender implements sender {
    @Override
    public void Send() {
        System.out.println("this sms message");
    }
}
View Code

Finally, build factories categories:

Package Penalty for pers.hupo.hupow.factory;

/ ** 
 * @author HUPO
 * Factory class
 * */
public class SendFactory {

    public Sender produce(String type) {
        if ("mail".equals(type)) {
            return new MailSender();
        }
        if ("sms".equals(type)) {
            return new SmsSender();
        }
        return null;
    }
}
View Code

testing method

Package Penalty for pers.hupo.hupow.factory;



public class FactoryTest {
    public static void main(String[] args) {
        SendFactory sendFactory = new SendFactory();
        Sender sender = sendFactory.produce("sms");
        sender.Send ();
    }
}
View Code

Output:

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/hupo-wey/p/11672418.html