In a simple factory mode, the factory class dynamically determines which product class instance should be created based on the parameters passed in by the factory method.
Code:
// Abstract product class TVpublic interface TV {public void play ();}
// Specific product class public class HaierTV implements TV {@ Overridepublic void play () {System. out. println ("Haier TV playing .......... ");}}
// Specific product class: public class HisenseTV implements TV {public void play () {System. out. println ("Hisense TV playing ........ ");}}
// The factory class produces different sets of public class TVFactory {public static TV producedTV (String brand) throws Exception {if (brand. equalsIgnoreCase ("Haier") {System. out. println ("the TV factory produces Haier TV sets! "); Return new HaierTV ();} else if (brand. symbol signorecase (" Hisense ") {System. out. println (" TV factory produces Hisense TV! "); Return new HisenseTV ();} else {try {throw new Exception (" sorry, this brand of TV cannot be produced now! ");} Catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} return null ;}}
Import java. io. file; import javax. xml. parsers. documentBuilder; import javax. xml. parsers. documentBuilderFactory; import org. w3c. dom. document; import org. w3c. dom. node; import org. w3c. dom. nodeList; public class XMLUtilTV {// XML operation tool class public static String getBrandName () {try {// create Document Object DocumentBuilderFactory dFactory = DocumentBuilderFactory. newInstance (); DocumentBuilder dBuilder = dFactory. newDocumentBuilder (); Document doc; doc = dBuilder. parse (new File ("configTV. xml "); // obtain the text node NodeList nl = doc that contains the brand name. getElementsByTagName ("brandName"); Node classNode = nl. item (0 ). getFirstChild (); String brandName = classNode. getNodeValue (). trim (); return brandName;} catch (Exception e) {// TODO: handle has tione. printStackTrace (); return null ;}}}
Public class Client {// test class public static void main (String [] args) {try {TV TV; // abstract type definition // obtain the brand String brandName = XMLUtilTV. getBrandName (); // obtain the specific product TV = TVFactory. producedTV (brandName); TV. play () ;}catch (Exception e) {// TODO: handle exception }}}