Home > Java > JavaBase > What are the three factory patterns in java?

What are the three factory patterns in java?

青灯夜游
Release: 2020-11-02 14:23:46
Original
5470 people have browsed it

Java's three factory patterns: 1. Simple factory pattern, which provides a function to create object instances without caring about its specific implementation; 2. Factory method pattern; 3. Abstract factory pattern, which provides a function to create an object instance. An interface for a family of related or interdependent objects without specifying their concrete classes.

What are the three factory patterns in java?

(Recommended tutorial: java introductory tutorial)

1. Simple factory pattern

Definition of simple factory: Provides a function to create object instances without caring about its specific implementation. The type of the created instance can be an interface, an abstract class, or a specific class

Implementing the car interface

public interface Car {
    String getName();
}
Copy after login

Benz class

public class Benz implements Car {
    @Override
    public String getName() {
        return "Benz";
    }
}
Copy after login

BMW type

public class BMW implements Car {
    @Override
    public String getName() {
        return "BMW";
    }
}
Copy after login

Simple factory that can produce both BMW and Mercedes-Benz

public class SimpleFactory {
    public Car getCar(String name){
        if (name.equals("BMW")){
            return new BMW();
        }else if (name.equals("benz")){
            return new Benz();
        }else {
            System.out.println("不好意思,这个品牌的汽车生产不了");
            return null;
        }
    }
}
Copy after login

Test class

public class SimpleFactoryTest {
    public static void main(String[] args){
        SimpleFactory simpleFactory = new SimpleFactory();
        Car car = simpleFactory.getCar("BMW");
        System.out.println(car.getName());
    }
}
Copy after login

Test result

BMW
Copy after login

According to the definition of a simple factory, users only need the product and don’t care how the product is produced, and it looks perfect. But think about it, are there any factories in this world that produce everything?

Obviously does not exist. Every car brand has its own production factory and its own production technology. Mapping to the spring framework, we have many types of beans that need to be produced. If we only rely on a simple factory to implement it, how many if..else ifs do we have to nest in the factory class?

Moreover, when we produce a car in the code, it just comes out with a new one, but in actual operation we don’t know how many operations are required. Loading, registration and other operations will be reflected in the factory class, so this class It will become chaotic and inconvenient to manage, so each brand should have its own production category.

Because it is dedicated, it is professional. At this time, the factory method appeared.

2. Factory method pattern

Factory interface

//定义一个工厂接口,功能就是生产汽车
public interface Factory {
    Car getCar();
}
Copy after login

Benz factory

public class BenzFactory implements Factory {
    @Override
    public Car getCar() {
        return new Benz();
    }
}
Copy after login

BMW Factory

public class BMWFactory implements Factory{
    @Override
    public Car getCar() {
        return new BMW();
    }
}
Copy after login

Test category

public class FactoryTest {
   public static void main(String[] args){
       Factory bmwFactory = new BMWFactory();
       System.out.println(bmwFactory.getCar().getName());
       Factory benzFactory = new BenzFactory();
       System.out.println(benzFactory.getCar().getName());
   }
}
Copy after login

Test result

BMW
Benz
Copy after login

According to the above It can be seen from the code that cars of different brands are produced by different factories, and they seem to be perfect. But if you look at the test category, when a person wants to buy a BMW car (assuming there is no seller), then he has to go to the BMW factory to produce one for him, and a few days later he wants to buy a Mercedes-Benz. When buying a car, you have to go to the Mercedes-Benz factory to hire someone to produce it, which undoubtedly increases the complexity of the user's operation. So is there a user-friendly method? At this time, the abstract factory pattern appeared.

3. Abstract Factory Pattern

Abstract Factory

public abstract class AbstractFactory {

     protected abstract Car getCar();
     
     //这段代码就是动态配置的功能
     //固定模式的委派
     public Car getCar(String name){
        if("BMW".equalsIgnoreCase(name)){
            return new BmwFactory().getCar();
        }else if("Benz".equalsIgnoreCase(name)){
            return new BenzFactory().getCar();
        }else if("Audi".equalsIgnoreCase(name)){
            return new AudiFactory().getCar();
        }else{
            System.out.println("这个产品产不出来");
            return null;
        }
    }
}
Copy after login

Default Factory

public class DefaultFactory extends AbstractFactory {

    private AudiFactory defaultFactory = new AudiFactory();
    
    public Car getCar() {
        return defaultFactory.getCar();
    }

}
Copy after login

BMW Factory

public class BMWFactory extends AbstractFactory {
    @Override
    public Car getCar() {
        return new BMW();
    }
}
Copy after login

Benz Factory

public class BenzFactory extends AbstractFactory {
    @Override    public Car getCar() {
            return new Benz();
    }
}
Copy after login

Test Class


public class AbstractFactoryTest {
    public static void main(String[] args) {        
        DefaultFactory factory = new DefaultFactory();        
        System.out.println(factory.getCar("Benz").getName());            
    }
}
Copy after login

Test results

Benz
Copy after login

As can be seen from the above code, if the user needs a car, he only needs to go to the default factory to put forward his needs (incoming parameters ), you can get the products you want without having to find different production factories based on the products, which is convenient for users to operate.

Note: Some people sneer at design patterns, and some people respect them as gods, but I agree with them.

According to my rough understanding, the classic thing about design patterns is that it solves the pain of both the person who writes the code and the person who calls the code. Different design patterns are only applicable to Different scenarios. As for whether to use it or not, and how to use it, you need to consider it carefully.

But you shouldn’t use it just for the sake of using it. The subtleties can only be left to everyone to taste slowly.

For more programming-related knowledge, please visit: Programming Courses! !

The above is the detailed content of What are the three factory patterns in java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template