JAVA design pattern-Simple Factory (Simple Factory)

Simple Factory

When creating an object, it does not expose internal details to customers and provides a common interface for creating objects.

1) Let me give you a chestnut. When there is no factory, we want an Apple mobile phone and we need to create one by ourselves. (At this time, we want to create a mobile phone requires a lot of parts (parameters). Whenever we want a mobile phone, we have to prepare a lot of parts to create a mobile phone. This is very troublesome. Then if there is any possibility, I can get it if I want a mobile phone. , No matter what parts it needs, this is why the factory class comes from)

2) Now that there is a factory mode, you just want your mobile phone to be picked up directly from the factory. (I did not reflect the idea of ​​the parts in the case)


/**
 * 苹果系列
 */
public interface Apple {
    
    
}
public class Iphone12 implements Apple {
    
    
}
public class Iphone11 implements Apple {
    
    
}
public class Iphone10 implements Apple {
    
    
}

The following IphoneFactory is a simple factory implementation, which is called by all client classes that need to be instantiated.

public class IphoneFactory {
    
    
    public static Product createIphone(int type) {
    
    
        switch (type) {
    
    
          case 12:
             return new Iphone12();
          case 11:
             return new Iphone11();
          default:
             return new Iphone10();
        }
    }
}

Customer category:

public class Consumer {
    
    

    public static void main(String[] args) {
    
    
        Apple iphone12 = IphoneFactory.createIphone(12);
    }
}

The simple factory pattern is also called the static factory method pattern. It can be seen from the naming that this pattern is very simple, that is, a class (factory) is used to provide an interface for creating objects.

Guess you like

Origin blog.csdn.net/weixin_43957211/article/details/110661737