java factory method details and example code

  • 2020-06-01 09:57:03
  • OfStack

Overview of factory methods

In the factory method pattern, the abstract factory class is responsible for defining the interface to create the object, and the concrete object creation is implemented by the concrete class that inherits the abstract factory.

advantages

The client side does not need to be responsible for the creation of objects, thus clarifying the responsibilities of each class. If new objects are added, only a specific class and a specific factory class need to be added, which does not affect the existing code, easy maintenance in the later stage, and enhances the extensibility of the system

disadvantages

Additional coding is required to increase the subwork


public class IntegerDemo {
  public static void main(String[] args) {
    Factory factory = new DogFactory();
    Animal animal = factory.createAnimal();
    animal.eat();
 
    factory = new CatFactory();
    animal = factory.createAnimal();
    animal.eat();
  }
}
 
abstract class Animal {//  An abstract class 
  public abstract void eat();
}
 
class Dog extends Animal {//  The dog 
  public void eat() {
    System.out.println("a dog is eatting.");
  }
}
 
class Cat extends Animal {//  The cat 
  public void eat() {
    System.out.println("a cat is eatting.");
  }
}
 
interface Factory {//  interface 
  public abstract Animal createAnimal();
}
 
class DogFactory implements Factory {//  Implementing an interface 
  public Animal createAnimal() {
    return new Dog();
  }
}
 
class CatFactory implements Factory {//  Implementing an interface 
  public Animal createAnimal() {
    return new Cat();
  }
}

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: