23 Design Patterns in Java--Factory Pattern

First, the classification of design patterns

Generally speaking, design patterns are divided into three categories :

There are five types of creational patterns : factory method pattern, abstract factory pattern , singleton pattern, builder pattern, and prototype pattern.

There are seven structural patterns : adapter pattern, decorator pattern, proxy pattern, appearance pattern, bridge pattern, composition pattern, and flyweight pattern.

There are eleven behavioral patterns : strategy pattern, template method pattern, observer pattern, iteration sub pattern, responsibility chain pattern, command pattern, memorandum pattern, state pattern, visitor pattern, mediator pattern, and interpreter pattern.

In fact, there are two types: concurrent mode and thread pool mode.

1. Factory Method

There are three types of factory method patterns: common factory pattern, multi-factory pattern, and static factory pattern.

1.1, common factory mode

It is to create a factory class to create instances of some classes that implement the same interface. First look at the relationship diagram:image

An example is as follows: (Let's take an example of sending emails and text messages) First, create a common interface for the two:

public interface Sender {  
    public void Send();  
} 

Second, create the implementation class:

public class MailSender implements Sender {  
    @Override  
    public void Send() {  
        System.out.println("this is mailsender!");  
    }  
} 
public class SmsSender implements Sender {  
  
    @Override  
    public void Send() {  
        System.out.println("this is sms sender!");  
    }  
}  

Finally, build the factory class:

public class SendFactory {  
  
    public Sender produce(String type) {  
        if ("mail".equals(type)) {  
            return new MailSender();  
        } else if ("sms".equals(type)) {  
            return new SmsSender();  
        } else {  
            System.out.println("请输入正确的类型!");  
            return null;  
        }  
    }  
} 

Under test:

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

1.2, multiple factory method patterns,

It is an improvement to the common factory method pattern. In the common factory method pattern, if the passed string is wrong, the object cannot be created correctly, while the multiple factory method pattern provides multiple factory methods to create objects separately. relation chart:image

Modify the above code and change the SendFactory class, as follows:

public class SendFactory {  
   public Sender produceMail(){  
        return new MailSender();  
    }  
      
    public Sender produceSms(){  
        return new SmsSender();  
    }  
}  

The test class is as follows:

public class FactoryTest {  
  
    public static void main(String[] args) {  
        SendFactory factory = new SendFactory();  
        Sender sender = factory.produceMail();  
        sender.Send();  
    }  
}  

Output: this is mailsender!

1.3, static factory method pattern,

Set the methods in the above multiple factory method patterns as static, and you can call them directly without creating an instance.

public class SendFactory {  
      
    public static Sender produceMail(){  
        return new MailSender();  
    }  
      
    public static Sender produceSms(){  
        return new SmsSender();  
    }  
}  

The test class is as follows:

public class FactoryTest {  
  
    public static void main(String[] args) {         
        //因为是静态方法,无需创建工厂类对象
        Sender sender = SendFactory.produceMail();  
        sender.Send();  
    }  
}  

Output: this is mailsender!

In general, the factory pattern is suitable: when a large number of products need to be created and have a common interface, the factory method pattern can be used to create them.

In the above three modes, if the incoming string is wrong, the normal factory mode cannot create the object correctly. Compared with the multiple factory method mode , the static factory method does not need to instantiate the factory class. Therefore, in most cases, We will choose the third one - the static factory method pattern.

2. Abstract Factory

One problem with the factory method pattern is that the creation of classes depends on the factory class. That is to say, if you want to extend the program, you must modify the factory class, which violates the closure principle. Therefore, from a design point of view, there are certain problems. ,How to solve? Just use the abstract factory pattern to create multiple factory classes, so that once you need to add new functions, you can directly add new factory classes without modifying the previous code. Because the abstract factory is not easy to understand, it is easier to understand if we look at the diagram first, and then combine the code.image

  • There is an error in the above figure. The SmsSendFactory in the first line should be MailSendFactory.

example:

public interface Sender {  
    public void Send();  
}  

Two implementation classes:

public class MailSender implements Sender {  
    @Override  
    public void Send() {  
        System.out.println("this is mailsender!");  
    }  
}  
public class SmsSender implements Sender {  
  
    @Override  
    public void Send() {  
        System.out.println("this is sms sender!");  
    }  
}  

Two factory classes:

public class SendMailFactory implements Provider {  
      
    @Override  
    public Sender produce(){  
        return new MailSender();  
    }  
} 
public class SendSmsFactory implements Provider{  
  
    @Override  
    public Sender produce() {  
        return new SmsSender();  
    }  
} 

In providing an interface:

public interface Provider {  
    public Sender produce();  
} 

Test class:

public class Test {  
  
    public static void main(String[] args) {  
        Provider provider = new SendMailFactory();  
        Sender sender = provider.produce();  
        sender.Send();  
    }  
}  

In fact, the advantage of this mode is that if you want to add a function now: send timely information, you only need to make an implementation class, implement the Sender interface, and at the same time make a factory class, implement the Provider interface, it is OK, no need to change the ready-made code. Doing so, expands better!

Other Design Pattern Links:

(Abstract) Factory Pattern

singleton pattern

builder mode

prototype mode

adapter mode

Decorator pattern

proxy mode

Appearance Mode

bridge mode

Combination mode

flyweight pattern

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325243505&siteId=291194637