package com.spsoft.factory;
public class FactoryDemo {
public static void main(String[] args) {
Car car = Factory.getCarInstance("Toyota");
if (car != null) {
car.start();
car.stop();
}
}
}
class Factory {
public static Car getCarInstance(String type) {
Car car = null;
try {
car = (Car) Class.forName("com.spsoft.factory." + type)
.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return car;
}
}
interface Car {
public void start();
public void stop();
}
class Benz implements Car {
public void start() {
System.out.println("Benz start...");
}
public void stop() {
System.out.println("Benz stop...");
}
}
class Ford implements Car {
public void start() {
System.out.println("Ford start...");
}
public void stop() {
System.out.println("Ford stop...");
}
}
class Toyota implements Car {
public void start() {
System.out.println("Toyota start...");
}
public void stop() {
System.out.println("Toyota stop...");
}
}