假如有一个工厂专门生成car,我们叫他carFactory ,而我们有两种车型分别是BMW 和AUDI,我们叫他BMWCar和AudiCar,但是我们发现Car有着很高的相似性,那我们就用java的接口抽象出一个Car
public interface Car {所有的车类都要实现这个接口
//一辆车可以运行
public void run();
}
1.BMWCar
public class BMWCar implements Car{
public void run() {
System.out.println("开着bmw飞奔而去!!!");
}
}
2.AudiCar
public class AudiCar implements Car{现在我们要定义一个简单工厂来生成car ,我们叫他simpleFactory
public void run() {
System.out.println("开着audi飞奔而去");
}
}
public class SimpleFactory {
public Car createCar(String carType){
Car car = null;
if(carType=="BMW"){
car = new BMWCar();
}else if(carType=="Audi"){
car = new AudiCar();
}
return car;
}
}
让我们的carFactory来生成我们的car了
public class CarFactory {现在要让我们的car跑起来了
private Car car;
SimpleFactory simpleFactory;
public CarFactory(SimpleFactory simpleFactory){
this.simpleFactory = simpleFactory;
}
public Car createCar(String carType){
Car car = null;
car = this.simpleFactory.createCar(carType);
return car;
}
}
public class Main {
public static void main(String[] args){
System.out.println("我要一辆bmw....");
SimpleFactory simple = new SimpleFactory();
CarFactory carFactory = new CarFactory(simple);
carFactory.createCar("BMW").run();
System.out.println("BMW生产完成");
System.out.println("我要一辆Audi....");
carFactory.createCar("Audi").run();
System.out.println("Audi生产完成");
}
}
简单工厂模式就是这样的。来看看我们的车出来了
我要一辆bmw....
开着bmw飞奔而去!!!
BMW生产完成
我要一辆Audi....
开着audi飞奔而去
Audi生产完成