Getting Started with java Simple Factory Mode
- 2021-11-02 00:46:04
- OfStack
Preface
Define a factory class, which can return instances of different classes according to different parameters. The created instances usually have a common parent class
The method used to create an instance in a simple factory pattern is usually a static (static) method, so the simple factory pattern is called a static factory method (Static Factory Method) and only needs to pass in a correct parameter to get the desired object without knowing its implementation process
Example
Take beverage processing factory as an example
1. Create a drink interface (or abstract class)
public interface Drink {
void production();
}
2. Realization of specific beverages (Coke, Sprite)
public class ColaDrinkProduction implements Drink{
@Override
public void production() {
System.out.println(" Production of cola drinks ");
}
}
public class SpriteDrinkProduction implements Drink{
@Override
public void production() {
System.out.println(" Production of Sprite Beverage ");
}
}
3. Beverage production factories
public class DrinkProductionFactory {
public static Drink productionDrink(String type){
switch (type){
case "cloa":
return new ColaDrinkProduction();
default:
return new SpriteDrinkProduction();
}
}
}
4. Factory call
What object needs to pass in the corresponding parameters
Drink cloa = DrinkProductionFactory.productionDrink("cloa");
cloa.production();
Characteristic
It is a concrete class, not an interface abstract class. There is an important call method (productionDrink), which is usually static. Create a product with if or switch and return
Disadvantages
Poor expandability I want to add one kind of beverage. Besides adding one kind of beverage product, I also need to modify the factory method (adding the branch condition of 'Case'). So it is not only open to expansion, but also open to modification, which violates the open-closed principle
Summarize
This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!