This article is excerpted from the book "easy to learn Design Patterns ".
I. Simple factory Model
1. Animal Management System example
Public interface animal {public void eat ();} public class tiger implements animal {public void eat () {sysout. out. println ("tiger eat") ;}; public void run () {sysout. out. println ("") ;};} public class doldolphin implements animal {public void eat () {sysout. out. println ("dolphins eat") ;}; public void swim () {sysout. out. println ("dolphins can swim") ;};} public class samplefactory {public static animal createanimal (string animalname) {If ("Tiger ". equals (animalname) {return New triger ();} else if ("doldolphin ". equals (animalname) {return New doldolphin () ;}} public class client {public static void main (string [] ARGs) {animal An = samplefactory. createanimal ("tiger");. eat (); An = samplefactory. createanimal ("doldolphin");. eat ();}}
2. Brief introduction to the simple factory Model
Simple factory mode is also called static factory mode, which defines a specific factory class
Creates some class instances, and these classes should have a common parent class,
In this way, abstract rather than specific programming can be oriented.
The simple factory mode consists of three parts: the factory class, the abstract class, and the concrete class that implements the abstract class.
Schematic diagram of the simple factory mode:
3. Advantages and disadvantages of the simple factory Model
Advantages:
In the simple factory mode, the client is no longer responsible for object creation, but instead is responsible for throwing this responsibility
For the factory class, the client is only responsible for object calls, thus clarifying the responsibilities of each class.
Disadvantages:
Because static methods are used to create objects in simple factory mode, static methods cannot be inherited.
On the other hand, this foreman class is responsible for the creation of all classes, which will lead to
In addition, the client may have different requirements on the Creation methods of some products. In this case,
It is necessary to constantly modify the factory class and determine the logic of the regular price, which is not conducive to later maintenance.