Antecedents feed
Previously, WE don’t know what to do. Previously, we didn’t know what to do.
As mentioned in the last episode, Xiao Guang quit his job and started a hot and dry noodle shop. He transformed the construction process of hot and dry noodle with Builder mode, which became increasingly stable and effective, and his business was getting better and better.
But Xiao Guang is a student who is good at observing, and he found that hot and dry noodles are really dry (it seems that ordinary people can also find it, grimface ~). I thought, it’s time to launch something new to solve users’ pain points.
So he decided to launch his own guangshi beverage product.
Beverage making
After a survey and visit, light found several characteristics:
- People do not have high requirements for this drink (code farmers diaosi characteristics ah), mainly thirst quenching.
- Because rush to go to work, general request to be quick, best can take away directly.
- Variety should be rich, people taste different ah.
Hence, small light chose the newest XX brand (have advertiser look for me? Ha ha. Instant drink. The process of making the drink is very simple. Soon, Xiao Guang makes his first drink — orange juice:
public class OrangeJuice {
public void make(a) {
// 1. Take out a disposable beverage cup
System.out.println("Take out the disposable beverage cups.");
// 2. add instant orange juice powder
System.out.println("Add instant orange juice powder.");
// 3. Add water and rinse
System.out.println("Water");
// 4. Cover and pack
System.out.println("Seal and pack."); }}Copy the code
Little Light thought
It looks like the program is working, let’s go into production… However, xiao Guang he Xu person, after all, is in the code of agriculture mixed for a number of years of comrade ah. Before it was put into use, there were “problems “:
There are many different kinds of drinks, and the process is similar, but the instant packets are different. If I did this for every one of my drinks, and someone came to me with an AD, and I put a QR code on the cup, wouldn’t I have to change the process for every one of my drinks
In a flash of inspiration, Little Light remembered the abstraction and encapsulation mentioned in object-oriented thought, so little light rewrote his own program:
He abstracts out a “Drink” class:
public abstract class Drink {
public void make(a) {
// 1. Take out a disposable beverage cup
System.out.println("Take out the disposable beverage cups.");
// 2. add instant orange juice powder
System.out.println("Join" + getInstantPackage());
// 3. Add water and rinse
System.out.println("Water");
// 4. Cover and pack
System.out.println("Seal and pack.");
}
abstract String getInstantPackage(a);
}Copy the code
Cola, plum soup, orange juice all inherited:
public class Coke extends Drink {
@Override
String getInstantPackage(a) {
return "Instant Coke powder"; }}public class PlumJuice extends Drink {
@Override
String getInstantPackage(a) {
return "Instant sour plum powder"; }}public class OrangeJuice extends Drink {
@Override
String getInstantPackage(a) {
return "Instant orange juice powder"; }}Copy the code
On sale
When the drink is ready to be sold, it goes like this:
public class XiaoGuang {
public static void main(String[] args) {
OrangeJuice orangeJuice = newOrangeJuice(); orangeJuice.make(); }}Copy the code
The next day, business is so good, xiao Guang asked her cousin to help make drinks temporarily. And, light also found that they do not need to pay attention to what users want to drink, directly let the user tell cousin, cousin directly to make drinks for users ~
Cousin is responsible for producing drinks according to user requirements:
public class Cousins {
public static Drink create(String drinkType) {
// Starting with Java7, switch supports String
switch (drinkType) {
case "Orange juice":
return new OrangeJuice();
case "Plum soup":
return new PlumJuice();
case "Coke":
return new Coke();
default:
return newOrangeJuice(); }}}Copy the code
Light no longer focuses on specific drinks:
public class XiaoGuang {
public static void main(String[] args) {
Drink drink = Cousins.create("Coke"); drink.make(); }}Copy the code
After adding the beverage set, the business is getting better and better as expected, it is estimated that there is also a beauty to assist the addition, ha ha…
After the story
For those of you who may have noticed a bit of familiarity, let’s express these relationships in UML:
In this case, it should be clear that this is our topic for today – simple factories.
Strictly speaking, a simple factory is not a design pattern, but a coding habit.
So why do we use simple factories, or what are the benefits of doing so?
From our example, we can see that Xiaoguang (Client class) does not need to pay attention to the process of Drink make, and has more time to receive customers. Instead, she only needs to get corresponding drinks from her cousin (factory class) and give them to customers.
This is the idea of programming with a single responsibility:
- Xiao Guang’s job is to receive clients
- The cousin’s duty is to brew drinks
Simple factory Generally, a static method is used to produce products, so it is sometimes called the static factory method pattern.
Further reading
In the course of this story, we mentioned object-oriented abstraction, encapsulation features. In fact, all of our OOD principles and design patterns are based on the idea of object-oriented, inseparable from the characteristics of abstraction, encapsulation, inheritance, polymorphism. With the analysis of these design patterns, we can also deepen the thought of object-oriented programming.
Glide, for example, one of the DefaultConnectivityMonitorFactory. Java is a similar simple factory implementation:
public class DefaultConnectivityMonitorFactory implements ConnectivityMonitorFactory {
@NonNull
public ConnectivityMonitor build( @NonNull Context context, @NonNull ConnectivityMonitor.ConnectivityListener listener) {
final int res = context.checkCallingOrSelfPermission("android.permission.ACCESS_NETWORK_STATE");
final boolean hasPermission = res == PackageManager.PERMISSION_GRANTED;
if (hasPermission) {
return new DefaultConnectivityMonitor(context, listener);
} else {
return newNullConnectivityMonitor(); }}}Copy the code
This is similar to the implementation of the Cousin Cousins Factory, except that what the Factory creates is not determined by the parameters passed in, but by internal logic.
To make it clearer:
What I’ve been saying for a long time: Architecture, design patterns are all ideas. There is no fixed formula. All of these formulas are to get us started, to understand the basic idea of object orientation, and then to be able to use the invisible. ‘.
Leave a tail
As you may have noticed, the disadvantages of a simple factory are also many. The cousin (factory) has too much responsibility, including (UML dependencies) all the implementation of the specific product. In addition, if we need to modify or add products, we have to change the implementation of the factory class. This is a clear violation of the open close principle.
Therefore, simple factories, in general, are suitable for a small number of product categories, and fixed scenarios.