This is the fifth day of my participation in the More text Challenge. For details, see more text Challenge

First, know the factory model

1.1 an overview of the

Today, you’ll learn about the second creator pattern in the design pattern, the Factory Method.

As usual, go to Baidu Encyclopedia to define:

The factory pattern is one of the most common examples of instantiating objects. It is a pattern that replaces new operations with factory methods. The famous Jive forum, for example, makes extensive use of the factory pattern, which can be seen everywhere in the Java application system. A =new A() A =new A() A =new A() A =new A() A =new A() A =new A() A =new A() But it will give your system more scalability with fewer changes.

Through the baidu encyclopedia, we know that one of the most common use new operation to create an instance, may not be the best strategy for an instance, each time a new object, it will have a series of complex initialization process, such as to open up space in memory, the variable is initialized, and check the calibration operation configuration files, and so on, Repeat the new object is equivalent to what we are doing the moon cake, if manual every time to do it, then put the dough in filling, then knead it into a circle, in carving, process is very complex, and use the factory pattern, after just need to put the filling of the dough can be copies made directly after the mold, mode of judgment in the factory, If it is to be engraved on the “happy” will use a happy mold to create, if it is to be engraved on the “Mid-Autumn Festival” will use the Mid-Autumn Festival mold to create.

In contrast to the factory pattern, we might define a class (moon cake mold) that is responsible for the creation of the object. Such a class is called the factory class. Wherever complex objects need to be generated, you can use the factory pattern to build them. In this way, the mold instance and the moon cake are separated, one is responsible for creating the instance, and one is responsible for using the instance.

1.2 Application Scenarios

  • The preparation for creating an object is complex, requiring initialization of many parameters, database queries, and so on.
  • The class itself has many subclasses, and the creation of these classes can easily change in the business, or the invocation of the class can easily change.

Classification:

  • 1. Simple factory mode
  • 2. Factory method mode
  • Abstract factory pattern

Second, simple factory mode

The biggest advantage of factory pattern is decoupling, which realizes the idea of interface-oriented programming. Define an interface for creating an object and let its subclasses decide which factory class to instantiate.

2.1 structure

The simple factory pattern is not a design pattern, but rather a programming habit.

A simple factory contains the following roles:

  • Abstract product: Defines the specification of the product, describing the main features and functions of the product
  • Concrete product: a subclass that implements or inherits from an abstract product
  • Concrete factory: Provides a method to create a product that the caller uses to get the product.

2.2 the use of

Create mooncakes with different words.

1. Create abstract interfaces

/** * define a mooncake mold interface */ public interface MoonCakeMould {// use the mold void use(); }Copy the code

Create a subclass instance

Public class GoodMoon implements MoonCakeMould {@override public void use() {system.out.println (" implements MoonCakeMould "); } public GoodMoon(){ this.use(); }} public class implements MoonCakeMould {@override public void use() {system.out.println (" implements MoonCakeMould "); ); } public NotBadMoon(){ this.use(); }}Copy the code

Create factory class:

Public class MoonCakeFactory {public MoonCakeMould makeMoon(String text){if(text.equals(" ")){return new GoodMoon(); }else if (text.equals(" happy Mid-Autumn festival ")){return new NotBadMoon(); } return null; } public static void main(String[] args) { MoonCakeFactory factory = new MoonCakeFactory(); MoonCakeMould moon = factory.makeMoon(" happy moon "); MoonCakeMould moon1 = factory.makemoon (" happy Mid-Autumn "); System.out.println(" +moon+"; Mold happy Mid-Autumn Festival: "+moon1); }}Copy the code

4. Output results:

The use of a happy Mid-Autumn Festival mold! Mold happy moon: patten.facotry.GoodMoon@33a10788; Die a happy Mid-Autumn festival: patten. Facotry. C658 NotBadMoon @ 7006Copy the code

2.3 the advantages and disadvantages

Advantages: The simple factory pattern encapsulates the process of creating an object and allows you to retrieve the object directly through parameters. By separating the creation of objects from the business logic layer, you can avoid changing the client code later. If you need to add a new product, you can change the factory class directly instead of changing it in the original code. This reduces the possibility of changing the client code and makes it easier to extend.

Disadvantages: Adding new products requires modifying the factory class code, which violates the “open closed principle” of adding a few if-else’s, so the simple factory pattern is suitable for situations where the business is simple and the factory class doesn’t change often.

3. Factory method mode

To solve the problem of modifying the simple factory pattern, we can build more factories so that we don’t need to modify the factory class. These factories inherit from the same abstract factory, so that the open closed principle is fully followed.

3.1 structure

The main roles of the factory method pattern are:

  • Abstract Factory: Declare a Factory method interface through which a caller accesses the Factory methods of a concrete Factory to create a product.
  • ConcreteFactory: Implements abstract methods in an abstract factory to create concrete products.
  • Abstract Product: Defines the specification of the product and describes the main features and functions of the product.
  • ConcreteProduct: Implements the interface defined by the abstract product role, created by concrete factories that correspond to one another.

3.2 implementation

1. Abstract factory

public interface MoonCakeFactory {
     MoonCakeMould makeMoon();
}
Copy the code

2, specific factory

public class GoodMoonCakeFactory implements MoonCakeFactory { @Override public MoonCakeMould makeMoon() { return new GoodMoon(); } } public class NotBadMoonCakeFactory implements MoonCakeFactory { @Override public MoonCakeMould makeMoon() { return new NotBadMoon(); }}Copy the code

3. Abstract products

Public interface MoonCakeMould {void use(); }Copy the code

4. Specific products

Public class implements MoonCakeMould {@override public void use() {system.out.println (" Implements MoonCakeMould "); public class implements MoonCakeMould {@override public void use() {system.out.println (" implements MoonCakeMould "); ); } public NotBadMoon(){ this.use(); }} public class GoodMoon implements MoonCakeMould {@override public void use() {system.out.println (" implements MoonCakeMould "); } public GoodMoon(){ this.use(); }}Copy the code

3.3 Analysis of Advantages and disadvantages

Advantages:

  • Solves the open closed principle without modifying the factory class
  • Users only need to know the name of the specific factory can get the desired product, without knowing the specific creation process of the product.

Disadvantages:

  • Adding a concrete class and a corresponding concrete factory class to each product adds to the complexity of the system.

Iv. Abstract factory pattern

Abstract factories were created to solve the factory pattern problem by minimizing the number of factory implementation subclasses. Instead of assigning an engineering class to each product, products can be grouped and then created in each group by different methods of the same factory class. For example, a real factory might make mobile phones, televisions and, more recently, cars!

So in the face of such a comprehensive and capable company, which can produce a variety of products, we can adopt the abstract factory model to consider multiple groups.

The abstract factory model will consider the production of multi-grade products and multi-brand products.

As shown above, the above simple classification by Millet and redrice, in fact, a product may have more classes, then if each class create an instance factory, such as the Picture of Xiaomi car factory class, Redrice car factory class…… And so on. That’s six factory classes.

4.1 structure

The main roles of the abstract factory pattern are as follows:

  • Abstract Factory: provides an interface to create a product. It contains multiple methods to create a product. It can create multiple levels of products. For example: millet mobile phone, red mi mobile phone, black shark game console and so on…..
  • Concrete Factory: Multiple abstract methods to realize the abstract Factory to complete the creation of Concrete products.
  • Abstract product: Defines the specification of the product and describes the main features and functions of the product. The abstract factory pattern has multiple abstract products.
  • Product: An interface that implements the abstract product role definition, created by a concrete factory. There is a many-to-one relationship with a specific factory.

4.2 implementation

1. Abstract factory

/** * abstract factory */ public interface TopFactory (); // Create RedMei createRedmiProduct(); }Copy the code

2. Specific factory (corresponding product family)

/** * implements TopFactory{@override public string PhoneFactory implements TopFactory () {return new XiaomiPhone(); } @Override public RedMei createRedmiProduct() { return new RedmiPhone(); }} /** * implements TopFactory {@override public string implements TopFactory () {return  new XiaomiTv(); } @Override public RedMei createRedmiProduct() { return new RedMiTv(); }}Copy the code

3. Abstract products (corresponding to the horizontal axis)

Public interface Xiaomi {void print(); } /** * public interface RedMei {void print(); }Copy the code

4, concrete class

public class RedMiTv implements RedMei { public RedMiTv(){ this.print(); } @override public void print() {system.out.println (" make a redrice phone "); } } public class RedmiPhone implements RedMei { public RedmiPhone(){ this.print(); } @override public void print() {system.out.println (" make a redrice phone "); } } public class XiaomiTv implements Xiaomi { public XiaomiTv(){ this.print(); } @override public void print() {system.out.println (" make a TV "); } } public class XiaomiPhone implements Xiaomi { public XiaomiPhone(){ this.print(); } @override public void print() {system.out.println (" make a Phone "); }}Copy the code

5, test,

public class test { public static void main(String[] args) { PhoneFactory phoneFactory = new PhoneFactory(); phoneFactory.createRedmiProduct(); TvFactory = new TvFactory(); tvFactory.createXiaomiProduct(); // Make a millet TV}}Copy the code

4.3 the advantages and disadvantages

Advantage: When multiple objects in a product family are worked together by the designer, it ensures that the client always uses only objects from the same product family.

Disadvantages: All factory classes need to be modified when a new product needs to be added to the product. For example, if a new black shark product is added, then the parent factory will add a method to create a black shark product, and other child factories will inherit and modify it.

Five, the summary

  • Simple factory: unique factory class, a product abstraction class, engineering class creation method based on input judgment.

  • Factory methods: Multiple factory classes, one abstract product class, use polymorphism to create different product objects, avoiding a lot of if-else judgments.

  • Abstract factory: Multiple factory classes, multiple product abstract classes, product subclasses group, the same factory implementation class creates the same group of different products, reducing the number of factory subclasses.

Factory mode usage scenarios:

1. The creation process of the object and the preparation of the instantiation are very complicated, and many parameters need to be initialized and the database needs to be queried.

2. The class itself has many subclasses, and the creation of these classes can easily change in the business, or the invocation of the class can easily change.

The getInstance() method in the DateForamt class uses the factory pattern.

4. The getInstance() method in the Calendar class uses the factory pattern;

In summary, the point of the factory pattern is: first, to facilitate the true decoupling of the instantiation process from the business logic, and second, to mask the complex object creation logic. The factory pattern is typically used to create complex objects. If simple objects can be created successfully by simply using new, you do not need to use the factory pattern, which would add complexity to the system.

This is the third article in the series of design patterns. The purpose of learning design patterns is to understand all kinds of elegant code design as soon as possible, and learn to use it. There is a long way to go, but the heart of search cannot be broken.