Creative Patterns: Factory Approach

Posted by FFEMTcJ on Tue, 07 May 2019 18:45:04 +0200

Article first
Creative Patterns: Factory Approach

brief introduction

Name: Factory Method

English name: Factory method Pattern

Values: Expansion is my monopoly

Personal introduction:

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Methods lets a class defer instantiation to subclasses. (Define an interface for creating objects, let subclasses decide which class to instantiate. Factory methods delay the instantiation of a class to its subclasses. )
(From Zen in Design Patterns)

The Story You Want

Remember the last article Singleton mode Is it the story in the story of ___________ Xiao Ming drives his car to travel, school and party. This time it's a continuation of Xiao Ming's story. One story can tell two design patterns. It's not easy. (Every time I think about stories, I want to break my head. Every article has at least three stories flashing through my mind, but there is only one suitable one left in the end, in order to explain the key points in the design pattern clearly and simply.)

Simple factory

Xiao Ming's family was not very rich before, but there was still a good garage in which all cars, motorcycles and bicycles were put. Every time Xiao Ming wants to go out, he will go to the garage and pick out the right car to start. For example, Xiao Ming took his final exam recently. He went to school by motorcycle. After the exam, Xiao Ming was going to travel. This time, he decided to travel by himself and drive his own car. This scenario is described in code.

public class SimpleFactoryTest {

    public static void main(String[] args) {
        XiaoMing xiaoMing = new XiaoMing();
        // Xiaoming goes to school by motorcycle
        IVehicle motorcycle = GarageFactory.getVehicle("motorcycle");
        xiaoMing.goToSchool(motorcycle);

        // Xiao Ming drives a car to travel
        IVehicle car = GarageFactory.getVehicle("car");
        xiaoMing.travel(car);
    }

}

/**
 * Garage
 */
class GarageFactory {

    public static IVehicle getVehicle(String type) {
        if ("car".equals(type)) {
            return new Car();
        } else if ("motorcycle".equals(type)) {
            return new Motorcycle();
        }
        throw new IllegalArgumentException("Please enter vehicle type");
    }

}

/**
 * Vehicle
 */
interface IVehicle {
    void run();
}

/**
 * automobile
 */
class Car implements IVehicle {

    @Override
    public void run() {
        System.out.println("Drive to...");
    }
}

/**
 * Motorcycle
 */
class Motorcycle implements IVehicle {

    @Override
    public void run() {
        System.out.println("Ride a motorcycle to...");
    }
}

class XiaoMing {

    public void goToSchool(IVehicle vehicle) {
        System.out.println("Xiao Ming goes to school");
        vehicle.run();
    }

    public void travel(IVehicle vehicle) {
        System.out.println("Xiao Ming goes traveling");
        vehicle.run();
    }

}

Do you understand the above code? Xiao Ming's family has a garage Garage Factory, which contains car Car and motorcycle Motorcycle. When Xiao Ming wants to go out, he goes to the garage to select a car, passes parameters to Garage Factory. getVehicle (), specifies what kind of car he wants, and then Xiao Ming sets out on his bicycle.

The real term for this code is Simple Factory Pattern, also known as static factory pattern. It is an implementation of factory method, which is the simplest implementation of factory method. It has a little flaw, that is, the scalability is not good enough. In the above code, Xiao Ming can only ride a motorcycle or drive a car, if Xiao Ming wants to ride a bicycle out? It is necessary to add if to Garage Factory, which is the logic of bicycle. Which rule does this violate? Is it the one that allows expansion and refuses modification? Opening and closing principle

It is not that simple factory is not a good way to achieve this, but that it is not scalable enough. In the normal development, simple factory mode is also used a lot. It is also appropriate to use a garage when there are not many cars in Xiaoming's house.

Factory method

Xiao Ming's father has made a lot of money in recent years. The two fathers and sons of car fans have been buying cars. There are more and more cars at home. At this time, they decided to build more garages and place them according to the type of car. For example, there is a garage, a motorcycle garage. At this time Xiao Ming will drive to the garage and ride a motorcycle to the garage. The code is implemented as follows.

public class FactoryMethodTest {

    public static void main(String[] args) {
        XiaoMing xiaoMing = new XiaoMing();
        // Xiaoming goes to school by motorcycle
        VehicleGarage motorcycleGarage = new MotorcycleGarage();
        IVehicle motorcycle = motorcycleGarage.getVehicle();
        xiaoMing.goToSchool(motorcycle);

        // Xiao Ming drives a car to travel
        VehicleGarage carGarage = new CarGarage();
        IVehicle car = carGarage.getVehicle();
        xiaoMing.travel(car);
    }

}

interface VehicleGarage {
    IVehicle getVehicle();
}

/**
 * Garage
 */
class CarGarage implements VehicleGarage {

    @Override
    public IVehicle getVehicle() {
        return new Car();
    }
}

/**
 * Motorcycle garage
 */
class MotorcycleGarage implements VehicleGarage {

    @Override
    public IVehicle getVehicle() {
        return new Motorcycle();
    }
}

The above code reuses the traffic interface of the simple factory implementation and the implementation classes of motorcycles and automobiles. There are two garages in the code, one is CarGarage garage and the other is Motorcycle Garage garage. If Xiao Ming wants to ride a bicycle, he only needs to build a bicycle garage without modifying the garage or motorcycle garage, which is very in line with the principle of opening and closing, and the expansion is greatly improved.

summary

The factory method pattern can be said to be a design pattern that you can think of in the open source framework source code, because the open source framework is very important to be scalable, and the factory method pattern is just scalable. Understanding the factory method model, it will be very handy to open the source code in the future.

Code Link: Factory method Pattern

Recommended reading

Single Responsibility Principle (Method: Change Name or Password? Interface: Washing dishes, buying vegetables or dumping garbage? Class: Registration, Log-in and Log-off)
Richter's Replacement Principle (My son comes from New Oriental Cuisine)
Depend on the inversion principle (stingy Hotel owner)
Interface Isolation Principle (Young Man's Workshop)
Dimiter's Law (Reading E-Books on Mobile Phones)
Open-Close Principle (Social Security)
Creative mode: Singleton mode (Xiaoming has only one car)

Backstage response to "Big Gift Pack" for Java, Python, IOS and other tutorials
Adding Personal Wechat Note "Tutorial" to Acquire Architects, Machine Learning and other Tutorials

Topics: Programming Mobile Java Python iOS