简单工厂模式,其实结合例子来说更容易理解。拿汽车举例子,Car首先是一个接口,有一些抽象的公共的方法。car1,car2……就可以实现这个接口。在做一个接口的类,将Car作为参数去判断car的类型,到底是car1,car2……。
下面看代码。
接口:
package carDemo;
public interface Car {
void stop();
void run();
}
汽车类1:
package carDemo;
public class Ford implements Car {
@Override
public void stop() {
System.out.println("ford has stopped");
}
@Override
public void run() {
System.out.println("ford is running");
}
}
汽车类2
package carDemo;
public class Bmw implements Car {
@Override
public void stop() {
System.out.println("bmw has stopped");
}
@Override
public void run() {
System.out.println("bmw is running");
}
}
汽车的工厂类
package carDemo;
public class CarFactory {
public static Car getCarInstance(String type){
Car car=null;
if ("ford".equalsIgnoreCase(type)) {
car=new Ford();
}else if("bmw".equalsIgnoreCase(type)){
car=new Bmw();
}
return car;
}
}
测试类
package carDemo;
public class Test {
public static void main(String[] args) {
Car car=CarFactory.getCarInstance("BMW");
car.stop();
}
}
下面改进汽车工厂类:通过反射找。
注意反射的类名的写法。Class.forName(“carDemo.”+type).newInstance();
package carDemo;
public class CarFactory {
public static Car getCarInstance(String type){
Car car=null;
try {
car=(Car) Class.forName("carDemo."+type).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return car;
}
}
测试类:
package carDemo;
public class Test {
public static void main(String[] args) {
Car car=CarFactory.getCarInstance("Bmw");
if (car!=null) {
car.stop();
}else{
System.out.println("sorry,please try another car brand!");
}
}
}