类图
java示例代码
1.车辆工厂接口
public interface CarFactory {
public Car produceCar() ;
}
2.宝马工厂类
public class BMWFactory implements CarFactory{
@Override
public Car produceCar() {
System.out.println("宝马工厂制造宝马车");
return new BMWCar();
}}
3.奔驰工厂类
public class BenzFactory implements CarFactory{
@Override
public Car produceCar() {
System.out.println("奔驰工厂制造奔驰汽车");
return new BenzCar();
}}
4.车辆接口
public interface Car {
public void run();
}
5.宝马车辆类
public class BMWCar implements Car{
@Override
public void run() {
System.out.println("宝马车在行驶");
}
}
6.奔驰车辆类
public class BenzCar implements Car{
@Override
public void run() {
System.out.println("奔驰车在行驶");
}}
7.客户端测试类
public class Client {
public static void main(String[] args) {
CarFactory factory;
Car car;
factory = new BMWFactory();
car = factory.produceCar();
car.run();
factory = new BenzFactory();
car = factory.produceCar();
car.run();
}
}