package com.lrq.factory;
public abstract class AbstractFactory {
public static AbstractFactory createFactory(String type){
if(type.equals("BMW")){
return new BMWFactory();
}else if(type.equals("Benz")){
return new BenzFactory();
}else{
throw new RuntimeException(type+"工厂不存在");
}
}
public abstract Car createCar();
public abstract Bus createBus();
}
package com.lrq.factory;
public class BenzFactory extends AbstractFactory {
@Override
public Car createCar() {
return new BenzCar();
}
@Override
public Bus createBus() {
return new BenzBus();
}
}
package com.lrq.factory;抽象的产品类:
public class BMWFactory extends AbstractFactory {
@Override
public Car createCar() {
return new BMWCar();
}
@Override
public Bus createBus() {
return new BMWBus();
}
}
抽象产品的实现类:
package com.lrq.factory;
public abstract class Bus {
public abstract void run();
}
package com.itheima.factory;
public abstract class Car {
public abstract void run();
}
package com.lrq.factory;
public class BMWBus extends Bus {
@Override
public void run() {
System.out.println("宝马卡车在跑呢");
}
}
package com.lrq.factory;
public class BMWCar extends Car {
@Override
public void run() {
System.out.println("奔驰轿车在跑呢");
}
}
package com.lrq.factory;
public class BenzBus extends Bus{
@Override
public void run() {
System.out.println("奔驰卡车在跑呢");
}
}
package com.lrq.factory;
public class BenzCar extends Car {
@Override
public void run() {
System.out.println("奔驰轿车在跑呢");
}
}
测试类:
package com.lrq.factory;
import org.junit.Test;
public class FactoryTest {
@Test
public void test() {
AbstractFactory factory = AbstractFactory.createFactory("BMW");
Bus bus = factory.createBus();
Car car = factory.createCar();
bus.run();
car.run();
}
}
<script type="text/javascript" id="wumiiRelatedItems"> </script>