Purpose: Provides an interface to create a family of interdependent objects without explicitly stating the entity class.
When to use:
- A system should not rely on the details of how a product class instance is created, composed, and expressed, which is important for all forms of Factory mode.
- The product of this system has more than one product family, and the system only consumes the products of one of the families.
- Products belonging to the same product family are used together, and this constraint must be reflected in the design of the system.
- The system provides a library of product classes, with all products appearing on the same interface, so that clients do not rely on implementations.
Practical Examples:
- Javax.xml.parsers.DocumentBuilderFactory
Example code:
public class App {public static void main (string[] args) {createkingdom (New elfkingdomfactory ()); Createkingdom (new Orckingdomfactory ());} public static void Createkingdom (Kingdomfactory factory) {King King = factory.createking (); Castle Castle = Factory.createcastle (); Army Army = Factory.createarmy (); System.out.println ("The kingdom was created."); System.out.println (king); System.out.println (Castle); System.out.println (Army);}}
Public interface King {}public interface Castle {}public interface Army {}public interface Army {}
<pre name= "code" class= "Java" >public interface Kingdomfactory {Castle createcastle (); King createking (); Army createarmy ();}
public class Elfkingdomfactory implements Kingdomfactory {public Castle createcastle () {return new Elfcastle (); Public King createking () {return new elfking ();} Public Army Createarmy () {return new Elfarmy ();}}
public class Orckingdomfactory implements Kingdomfactory {public Castle createcastle () {return new Orccastle (); Public King createking () {return new orcking ();} Public Army Createarmy () {return new Orcarmy ();}}
public class Elfarmy implements Army {@Overridepublic String toString () {return ' This is the Elven army! ';}}
public class Elfking implements King {@Overridepublic String toString () {return ' This is the Elven king! ';}}
public class Elfcastle implements Castle {@Overridepublic String toString () {return ' This is the Elven castle! ';}}
public class Orcarmy implements Army {@Overridepublic String toString () {return ' This is the Orcish army! ';}}
public class Orccastle implements Castle {@Overridepublic String toString () {return ' This is the Orcish castle! ';}}
public class Orcking implements King {@Overridepublic String toString () {return ' This is the ORC king! ';}}
Output Result:
The kingdom was created. This is the elven king! This is the elven castle! This is the elven army! The kingdom was created. This is the ORC king! This is the Orcish castle! This is the Orcish army!
Panda with Big Bucket
Java design mode-abstract Factory mode (Factory)