I. Definition
From the type of design pattern, the simple factory pattern belongs to the creation pattern, also known as static Factory method (static Factory methods), but not one of the 23 gof design patterns. A simple factory pattern is a factory object that determines which instances of the product class are created. The simple factory pattern is the simplest and most practical pattern in the factory model family, and can be understood as a special implementation of different factory patterns.
Two. To achieve
/**
* 1, define an interface----abstract products
* 2, definition of the implementation of the interface of the class----specific products
* 3, define a class to be a specific product management, used to create objects for specific products to prepare----factory
*
* Abstract Product (interface)
*↓
* Specific products (Class) ← Factory (static method)
*
*/
Abstract interface Fruit public interface Fruit {
public void plant ();
public void grow ();
public void Harvest ();
}
Specific Product class
Public class Apple implements fruit{
@Override
public void plant () {
System.out.println ("Growing Apple");
}
@Override
public void Grow () {
System.out.println ("apple Growth");
}
@Override
public void Harvest () {
System.out.println ("Harvest Apple");
}
public class Grape implements Fruit {
Private boolean seedless;
public Boolean isseedless () {
return seedless;
}
public void Setseedless (Boolean seedless) {
this.seedless = seedless;
}
@Override
public void plant () {
System.out.println ("Grapes planted");
}
@Override
public void Grow () {
System.out.println ("Grape Growth");
}
@Override
public void Harvest () {
System.out.println ("Harvest Grapes");
}
}
public class Strawberry implements Fruit {
@Override
public void plant () {
System.out.println ("Strawberry Growing");
}
@Override
public void Grow () {
SYSTEM.OUT.PRINTLN ("Strawberry Growth");
}
@Override
public void Harvest () {
System.out.println ("Harvest Strawberry");
}
}
Factory
public class Fruitgardner {
/**
* Static Factory method
*/
public static Fruit factory (String which) throws Exception {
if (Which.equalsignorecase ("Apple")) {
Return to New Apple ();
}else if (which.equalsignorecase ("Grape")) {
return new Grape ();
}else if (which.equalsignorecase ("Strawberry")) {
return new Strawberry ();
}else {
throw new Exception ("Fruit input error");
}
}
}