Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Creative model: factory approach

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

The first release of the article

Creative model: factory approach

Brief introduction

Name: factory method

English name: Factory method Pattern

Values: expansion is my exclusive

Personal introduction:

Define an interface for creating an object,but let subclasses decide which class to instantiate.Factory Method lets a class defer instantiation to subclasses. Define an interface for creating objects, and let the subclass decide which class to instantiate. The factory method delays the instantiation of a class to its subclass.)

(from the Zen of Design patterns)

The story you want.

Remember the story in the last singleton pattern? Xiao Ming drives a car to travel, go to school and go to parties. This time it is a continuation of Xiaoming's story, one story can tell two design patterns, it is not easy. Every time I think of a story, I want to break my head. Every article has at least three stories that flash through my mind, but in the end, there is only one suitable, in order to explain the key points of the design pattern more clearly and simply. )

Simple factory

Xiaoming's family was not very rich before, but there is still a good garage, where cars, motorcycles, bicycles and so on are kept. Every time Xiao Ming goes out, he will go to the garage to pick a suitable car to set off. For example, Xiao Ming recently took the final exam and went to school by motorcycle. After the exam, Xiao Ming was ready to travel. This time he decided to take a self-driving trip and drive his own car. Let's describe this scene in code.

Public class SimpleFactoryTest {public static void main (String [] args) {XiaoMing xiaoMing = new XiaoMing (); / Xiao Ming 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 car type") }} / * vehicles * / interface IVehicle {void run ();} / * cars * / class Car implements IVehicle {@ Override public void run () {System.out.println ("take the car.") ;}} / * * Motorcycle * / class Motorcycle implements IVehicle {@ Override public void run () {System.out.println ("go by motorcycle.") ;} 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 travel"); vehicle.run ();}}

Do you understand the code above? Xiaoming has a garage GarageFactory with a car Car and a motorcycle Motorcycle in it. When Xiaoming wants to go out, he chooses a car in the garage and passes parameters to GarageFactory.getVehicle () to indicate what car he wants, and then Xiaoming sets off on his bike.

The real term for this code is called simple factory pattern (Simple Factory Pattern), also known as static factory pattern. It is an implementation of the factory method, and it can be seen literally that it is the simplest implementation of the factory method. It has a small flaw, that is, the expansibility is not good enough. In the above code, Xiao Ming can only ride a motorcycle or drive a car. What if Xiao Ming wants to go out by bike? It is necessary to add if to GarageFactory as the logic of bicycle. Which rule is this against? Is it the opening and closing principle that allows expansion and refuses modification?

It is not that the implementation of simple factory is not good, but that it is not scalable enough, and the simple factory pattern is also used a lot in normal development. Under the circumstances that there are not many cars in Xiaoming's family, it is also appropriate to use a garage.

Factory method

Xiaoming's father has made a lot of money in recent years. The two father and son of car fans have been buying cars, and there are more and more cars in the family. 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, if Xiaoming wants to drive a car, he will go to the garage. If he wants to ride a motorcycle, he will go to the motorcycle garage. The code implementation is as follows.

Public class FactoryMethodTest {public static void main (String [] args) {XiaoMing xiaoMing = new XiaoMing (); / Xiao Ming 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 ();} / * * car 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 a simple factory implementation and the implementation classes of motorcycles and cars. There are two garages in the code, one is the car garage CarGarage, the other is the motorcycle garage MotorcycleGarage. If Xiaoming wants to ride a bike, he only needs to build a bicycle garage, and there is no need to modify the car garage or motorcycle garage, which is very consistent with the opening and closing principle and the expansibility is greatly improved.

Summary

The factory method pattern can be said to be a design pattern that is bound to be used in the source code of any open source framework you can think of, because it is important for the open source framework to be extensible, while the factory method pattern is extensible. Understand the factory method pattern, after looking at the source code is very handy.

Code link: Factory method Pattern

Recommended reading

Single responsibility principle (method: change the name or password? Interface: washing dishes, buying vegetables or taking out the trash? Classes: register, log in, and log out)

Richter substitution principle (my son is from New Oriental Cooking)

Rely on the principle of inversion (a stingy restaurant owner)

Interface isolation principle (young man's workshop)

Dimitt's rule (reading e-books on mobile phones)

The principle of opening and closing (social security)

Creative mode: singleton mode (Xiaoming has only one car)

The official account replied "Gift package" to get tutorials such as Java, Python, IOS, etc.

Add personal Wechat comments "tutorials" to get tutorials for architects, machine learning, etc.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report