1. Factory Method Mode1.1. Overview
In factory method mode, the abstract factory class is responsible for defining the interfaces that create objects, and the creation of specific objects is implemented by the concrete classes that inherit the abstract factory.
1.2. Advantages
- enhance the scalability of the system
The client does not need to be responsible for the creation of objects, thus clarifying the responsibilities of each class, if there are new objects added, only need to add a specific class and the specific factory class, do not affect the existing code, late maintenance easy, enhance the system extensibility
1.3. Disadvantages
- Additional writing code required, increased workload
2. Code
- Factory Interface: Factory.java
Package Cn.itcast_02;public interface Factory {public abstract Animal createanimal ();
- Animal Abstract class: Animal.java
Package Cn.itcast_02;public Abstract class Animal {public abstract void Eat ();}
- specific factory class-dog: Dogfactory.java
Package Cn.itcast_02;public class Dogfactory implements Factory {@Overridepublic Animal createanimal () {return new Dog (); }}
- specific Dog class: Dog.java
Package Cn.itcast_02;public Class Dog extends Animal {@Overridepublic void Eat () {System.out.println ("Dog eats Meat");}}
- specific factory class-Cat: Catfactory.java
Package Cn.itcast_02;public class Catfactory implements Factory {@Overridepublic Animal createanimal () {return new Cat (); }}
- specific cat type: Cat.java
Package Cn.itcast_02;public class Cat extends Animal {@Overridepublic void Eat () {System.out.println ("Cat eats Fish");}}
- Test class: Animaldemo.java
Package Cn.itcast_02;public class Animaldemo {public static void main (string[] args) {//requirement: I want to buy a dog factory F = new Dogfactor Y (); Animal a = F.createanimal (); A.eat (); System.out.println ("-------");//demand: I want to buy a cat F = new catfactory (); a = F.createanimal (); A.eat ();}}
Java Design pattern-factory method mode