1. Simple Factory mode1.1 Overview
Also called the static Factory method pattern, which defines a specific factory class that is responsible for creating instances of some classes.
1.2 Advantages
Clients do not need to be responsible for the creation of objects, thus clarifying the responsibilities of each class.
1.3 Disadvantages
This static factory class is responsible for the creation of all objects, if new objects are added, or some objects are created in different ways, it is necessary to constantly modify the factory class, not conducive to later maintenance
2. Code
- Animal Abstract class -animal.java
Package Cn.itcast_01;public Abstract class Animal {public abstract void Eat ();}
- Animal Factory-animalfactory.java
Package Cn.itcast_01;public class Animalfactory {private Animalfactory () {}//public static Dog Createdog () {//return new Dog ();//}////public static Cat Createcat () {//return new Cat ();//}public static Animal createanimal (String type) {if ("Dog". Equals (Type)) {return new Dog ();} else if ("Cat". Equals (Type)) {return new Cat ();} else {return null;}}}
- specific Dog class: Dog.java
Package Cn.itcast_01;public Class Dog extends Animal {@Overridepublic void Eat () {System.out.println ("Dog eats Meat");}}
- specific cat type: Cat.java
Package Cn.itcast_01;public class Cat extends Animal {@Overridepublic void Eat () {System.out.println ("Cat eats Fish");}}
- Test class: Animaldemo.java
Package Cn.itcast_01;public class Animaldemo {public static void main (string[] args) {//Specific class call dog D = new Dog ();d. Eat (); Cat C = new Cat (); c.eat (); System.out.println ("------------");//factory-made//DOG DD = Animalfactory.createdog ();//Cat CC = Animalfactory.createcat ();//Dd.eat ();//Cc.eat ()//System.out.println ("------------");//factory improved animal a = Animalfactory.createanimal ("dog"); A.eat (); a = Animalfactory.createanimal ("cat"); A.eat ();//Nullpointerexceptiona = Animalfactory.createanimal ("Pig"), if (a = null) {a.eat ();} else {System.out.println ("Sorry, this animal is not available for the time being");}}
Java design pattern-Simple Factory mode