PackageGongchangdemo;/** Use more of a design pattern in Java development: Factory mode: is a transition side * through the over-end to get interface instantiation object, this transition is called Factory Factory * This mode is mainly to solve the modification of subclasses, you must modify the Main method, And the main method is mainly the client, the client * often changed to go not very good, introduced: Factory mode*/ Public classGongchangdemo { Public Static voidMain (String args[]) {//the GetInstance method is static, so it can be called directly with the class name//Fruit F =null; //f = factory.getinstance ("Apple"); //f.eat (); //It says that Apple is fixed and can be used to initialize parameters by selecting any subclass to markFruit F =NULL; F= Factory.getinstance (args[0]); if(f!=NULL) {f.eat (); } }}//Write an interfaceInterfacefruit{//write an abstract class to eat Public Abstract voideat ();}//write a subclass to implement fruitclassAppleImplementsfruit{ Public voideat () {System.out.println ("I'm eating an apple."); }}//write another subclass to implement fruitclassOrangeImplementsfruit{ Public voideat () {System.out.println ("I'm eating oranges."); }}//Write a transition-class factory, get the instantiated object of the interfaceclassfactory{//returns the fruit type, so it is decorated with fruit Public StaticFruit getinstance (String classname) {//Initialize FirstFruit F =NULL; //the passed parameter is compared with the subclass name . if("Apple". Equals (classname)) {f=NewApple (); } if("Orange". Equals (classname)) {f=NewOrange (); } returnF; } }
Factory design patterns used in Java development