1. Abstract class
Package Com.zpark.service; /** @author*/Publicinterface environmental { Public void governanceenvironment ();}
2. Implementation class
package Com.zpark.service.impl; public class Beijingenvironmental implements environmental{@ Override public void Governanceenvironment () {System.out.println (" "method of Beijing Governance environment" "
package Com.zpark.service.impl; public class Tianjinenvironmental implements environmental{@ Override public void Governanceenvironment () {System.out.println (" "method of Tianjin Governance Environment" "
Package Com.zpark.service.impl; Public class Implements environmental{ @Override publicvoid governanceenvironment () { System.out.println ("The method of managing the environment in Hebei Province");} }
3, Simple factory class
PackageCom.zpark. Utils; Public classEnvironmentalsimplefactory {//creates an object based on a parameter, which is a static method that can be called directly using the class name Public StaticEnvironmental createsalary (String name) {Class<Environmental> Clazz =NULL; Environmental salary=NULL; Try { //gets the object of the class corresponding to the parameter using the reflection mechanismClazz = (class<environmental>) class.forname (name); //use such objects to create the corresponding environment class object, where the parent class pointer is used to point to the subclass object, which implements the polymorphicSalary =(environmental) clazz.newinstance (); }Catch(Exception e) {e.printstacktrace (); } returnsalary; }}
4. Test method
Packagecom.zpark.test;Importorg.junit.Test;/** * @authorCeshi * @Title: ${file_name} * @Package ${package_name} * @Description: ${todo} * @date 2018/6/818:53*/ Public classenvironmentaljunittest {@Test Public voidTest () {//Create a client object that calls the Computesalary () method to the type parameter NewEnvironmentaljunittest (). Computesalaryenvironmental ("Com.zpark.service.impl.BeijingEnvironmental"); NewEnvironmentaljunittest (). Computesalaryenvironmental ("Com.zpark.service.impl.HebeiEnvironmental"); NewEnvironmentaljunittest (). Computesalaryenvironmental ("Com.zpark.service.impl.TianjinEnvironmental"); } /*** Create different payroll objects by calling the factory class's creation environment governance method according to the parameters passed in@paramname*/ Public voidcomputesalaryenvironmental (String name) {//this uses polymorphism to generate zhejiangsalary or Hebeisalary objects depending on the parameters passed in.Environmental environmental =environmentalsimplefactory.createsalary (name); //methods for dynamically invoking a concrete class object using the generated objectenvironmental.governanceenvironment (); }}
5. Test results
Java Create simple Factory mode