package com.mhm.simplefactory;
/**
*
* @author Administrator
* @描述 抽象产品角色
*/
public interface Car {
public void drive();
}
package com.mhm.simplefactory;
/**
*
* @author Administrator
* @描述 奔驰车,具体产品角色
*/
public class Benz implements Car {
@Override
public void drive() {
System.out.println("开奔驰车");
}
}
package com.mhm.simplefactory;
/**
*
* @author Administrator
* @描述 宝马车,具体产品角色
*/
public class Bmw implements Car {
@Override
public void drive() {
System.out.println("开宝马车");
}
}
package com.mhm.simplefactory;
/**
*
* @author Administrator
* @描述 工厂类角色
*/
public class Driver {
public static Car driveCar (String carName) throws Exception {
if (carName.equalsIgnoreCase("benz")) {
return new Benz();
} else if (carName.equalsIgnoreCase("bmw")) {
return new Bmw();
} else {
throw new Exception("没有此车");
}
}
}
package com.mhm.simplefactory;
/**
* @描述 开车人
* @author Administrator
*
*/
public class Magnate {
public static void main(String[] args) {
try {
Car car = Driver.driveCar("bmw");
car.drive();
} catch (Exception e) {
e.printStackTrace();
}
}
}
当车多后,需要修改工厂类,这不符合开闭模式(对扩展开放,对修改封闭)
所以后续使用工厂方法模式。