//抽象产品角色
interface Car {
void drive();
}
// 具体产品角色
class Benz implements Car {
public void drive() {
System.out.println("Car Benz is starting");
}
}
class Bmw implements Car {
public void drive() {
System.out.println("Car Bmw is starting");
}
}
// 工厂类角色
class Driver {
public static Car driverCar(String string) throws Exception {
if (string.equalsIgnoreCase("Benz")) {
return new Benz();
} else if (string.equalsIgnoreCase("Bmw")) {
return new Bmw();
} else {
throw new Exception();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Car car = Driver.driverCar("Benz");
car.drive();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
工厂方法模式
优:产品和工厂都符合开闭原则
劣:当产品种类多的时候,工厂对象也会相应的增加。
//抽象工厂角色
interface Driver{
Car driverCar();
}
// 工厂类角色
class BenzDriver implements Driver{
public Car driverCar(){
return new Benz();
}
}
class BmwDriver implements Driver{
public Car driverCar(){
return new Bmw();
}
}
//使用者
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Driver driver = new BenzDriver();
Car car = driver.driverCar();
car.drive();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//抽象工厂
public abstract class AbstractFactory {
public abstract Car getCar(String car);
public abstract Tire getTire(String tire);
}
/*****************************/
//抽象产品 轮胎
public interface Tire {
void train();
}
//抽象产品
public interface Car {
void drive();
}
/*****************************/
//实体类 子午线轮胎
public class RadialTire implements Tire {
@Override
public void train() {
// TODO: 2019-08-19
}
}
//实体类 防滑轮胎
public class AntiskidTire implements Tire {
@Override
public void train() {
// TODO: 2019-08-19
}
}
/*****************************/
//创建实现接口的实体类
public class Benz implements Car {
@Override
public void drive() {
//todo Benz created
}
}
//创建实现接口的实体类
public class Audi implements Car {
@Override
public void drive() {
//todo Audi created
}
}
/*****************************/
//创建一个工厂创造器
public class FactoryProducer {
public static AbstractFactory getFactory(String choice) {
if (choice.equalsIgnoreCase("CAR")) {
return new CarFactory();
} else if (choice.equalsIgnoreCase("TIRE")) {
return new TireFactory();
}
return null;
}
}