----------------------------------------------公共的抽象父类或接口--------------------------------
public abstract class Car {
public abstract void start();
}
----------------------------------------------子类通过不同的方法实现了基类中的方法----------
----------------------------------------------子类BMW--------------------------------------------------
public class BMW extends Car {
/* (non-Javadoc)
* @see com.demofactory.Car#start()
*/
@Override
public void start() {
System.out.println("BMW start......");
}
}
----------------------------------------------子类Audi------------------------------------------------
public class Audi extends Car {
/* (non-Javadoc)
* @see com.demofactory.Car#start()
*/
@Override
public void start() {
System.out.println("Audi start......");
}
}
----------------------------------------------工厂类---------------------------------------------------
public class CarFactory {
// 生产车
public static Car buildCar(int i) {
if (i == 0) {
return new BMW();
} else {
return new Audi();
}
}
}
----------------------------------------------测试------------------------------------------------------
public class TestFactory {
public static void main(String[] args) {
//根据需要生产相应的车
Car car = CarFactory.buildCar(0);
car.start();
Car car1 = CarFactory.buildCar(1);
car1.start();
}
}
----------------------------------------------结果-----------------------------------------------------
BMW start......
Audi start......