Packagecom.simplefactory;/*** Operation class *@authorAdministrator **/ Public classOperation {Private DoubleNumbera; Private DoubleNumberb; Public DoubleGetresultvalue () {return0.0; } Public DoubleGetnumbera () {returnNumbera; } Public voidSetnumbera (DoubleNumbera) { This. Numbera =Numbera; } Public DoubleGetnumberb () {returnNumberb; } Public voidSetnumberb (DoubleNumberb) { This. Numberb =Numberb; } }
Package com.simplefactory; /** @author*/Publicclassextends operation { @Override Public Double Getresultvalue () { return getnumbera () + getnumberb ();} }
Package com.simplefactory; /** @author*/Publicclassextends operation { @Override Public Double Getresultvalue () { return getnumbera ()- getnumberb ();} }
Packagecom.simplefactory;/*** Simple Factory class *@authorAdministrator **/ Public classSimplefactory {Privateoperation Operation; PublicOperation Factoryoperate (String type) {if("+". Equals (Type) {Operation=Newaddition (); } Else if("-". Equals (Type) {Operation=NewSubtracter (); } returnoperation; }}
Packagecom.simplefactory;/*** Simple factory class, using reflection to achieve *@authorAdministrator **/ Public classSimplefactory_reflect {Privateoperation Operation; PublicOperation Factoryoperate (String ClassType) {Try{Operation= (operation) class.forname ("Com.simplefactory." +ClassType). newinstance (); } Catch(Exception e) {e.printstacktrace (); } returnoperation; }}
The point is that in reflection here, the reflection mechanism can not modify the factory class when adding new functions, just add the new method function name to the.
(GO) Java Simple Factory mode (implement a calculator)