2. Factory factory mode

The factory mode is to create objects based on different parameters. For example, use the factory creator. If we want a boy, the factory will produce a boy for us; if we need a girl, the factory will produce a girl for us. The factory will provide us with different items according to different parameters.

To instantiate the object, use the factory method instead of the new operation.

Define an interface to create objects, but let subclasses decide which classes need to be instantiated.

The factory method defers the work of instantiation to the subclass.

Factory pattern design

  1. Loose coupling as much as possible, and the change of an object's dependent objects has nothing to do with itself.
  2. The specific product is separated from the client and the responsibility is divided.

Code

 

interface Human {
    public void Talk();
    public void Walk();
}
 
class Boy implements Human{
    @Override
    public void Talk() {
        System.out.println("Boy is talking...");        
    }
 
    @Override
    public void Walk() {
        System.out.println("Boy is walking...");
    }
}
 
class Girl implements Human{
 
    @Override
    public void Talk() {
        System.out.println("Girl is talking...");   
    }
 
    @Override
    public void Walk() {
        System.out.println("Girl is walking...");
    }
}
 
public class HumanFactory {
    public static Human createHuman(String m){
        Human p = null;
        if(m == "boy"){
            p = new Boy();
        }else if(m == "girl"){
            p = new Girl();
        }
 
        return p;
    }
}

Common applications

Calendar object

According to different parameters, the getInstance() method will return different Calendar objects.

java.util.Calendar – getInstance()
java.util.Calendar – getInstance(TimeZone zone)
java.util.Calendar – getInstance(Locale aLocale)
java.util.Calendar – getInstance(TimeZone zone, Locale aLocale)
 
java.text.NumberFormat – getInstance()
java.text.NumberFormat – getInstance(Locale inLocale)

JDBC

Spring BeanFactory

BeanFactory, as the Ioc container based on Spring, is a Bean factory of Spring. If you think about it from the perspective of the factory model, it is used to "produce Beans" and then provide them to clients.

Suitable for the scene

  1. There is a group of similar objects that need to be created.
  2. It is not possible to foresee which instance of the class needs to be created when coding.
  3. The system needs to consider scalability and does not depend on the details of how product class instances are created, combined, and expressed.

 

 

 

 

 

Guess you like

Origin blog.csdn.net/sinat_37138973/article/details/88176421