//抽象產(chǎn)品角色
interface Car {
void drive();
}
// 具體產(chǎn)品角色
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();
}
}
工廠方法模式
優(yōu):產(chǎn)品和工廠都符合開閉原則
劣:當產(chǎn)品種類多的時候鬓长,工廠對象也會相應(yīng)的增加谒拴。
//抽象工廠角色
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);
}
/*****************************/
//抽象產(chǎn)品 輪胎
public interface Tire {
void train();
}
//抽象產(chǎn)品
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
}
}
/*****************************/
//創(chuàng)建實現(xiàn)接口的實體類
public class Benz implements Car {
@Override
public void drive() {
//todo Benz created
}
}
//創(chuàng)建實現(xiàn)接口的實體類
public class Audi implements Car {
@Override
public void drive() {
//todo Audi created
}
}
/*****************************/
//創(chuàng)建一個工廠創(chuàng)造器
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;
}
}