public interface Car {
String excute();
}
public class BenchiCar implements Car{
public String excute() {
System.out.println("奔驰车生产....");
return "OK";
}
}
public class BwmCar implements Car{
public String excute() {
System.out.println("宝马车生产....");
return "OK";
}
}
public class BydCar implements Car{
public String excute() {
System.out.println("比亚迪车生产....");
return "OK";
}
}
public class CarFactory {
public static Car getCar(String carType) {
Car car = null;
if ("benchi".equals(carType)) {
car = new BenchiCar();
} else if ("bwm".equals(carType)) {
car = new BwmCar();
} else if ("byd".equals(carType)) {
car = new BydCar();
}
return car;
}
}
public class SimpleFactoryDemo {标签:excute,String,Car,class,模式,工厂,简单,public,car From: https://www.cnblogs.com/NIAN2011/p/16618326.html
/**
* 1.定义抽象产品接口
* 2.定义具体产品实现类
* 3.定义生产工厂实现类及静态方法
* 4.demo测试
*
* 优点:不必关心类对象如何创建,实现了解耦,把初始化实例时的工作放到工厂里进行,使代码更容易维护
* 缺点:
* 1,一旦添加新产品就不得不修改工厂类的逻辑,这样就会造成工厂逻辑过于复杂
* 2,静态方法不能被继承和重写
* @param args
*/
public static void main(String[] args) {
Car benchi = CarFactory.getCar("benchi");
benchi.excute();
Car bwm = CarFactory.getCar("bwm");
bwm.excute();
Car byd = CarFactory.getCar("byd");
byd.excute();
}
}