汽车生产demo演示简单工厂和工厂模式
简单工厂
package factory.model;
public interface Car {
void run();
}
package factory.model;
public class Benz implements Car{
@Override
public void run() {
System.out.println("奔驰在跑");
}
}
package factory.model;
public class Bmw implements Car{
@Override
public void run() {
System.out.println("宝马在跑");
}
}
package designMode.factory;
import designMode.model.Benz;
import designMode.model.Bmw;
import designMode.model.Car;
public class SimpleFactory {
public static Car getCar(String brand){
if("benz".equals(brand)){
System.out.println("簡單工厂生产奔驰");
return new Benz();
}else if("bmw".equals(brand)){
System.out.println("簡單工厂生产宝马");
return new Bmw();
}
return null;
}
public static void main(String[] args) {
Car benz=SimpleFactory.getCar("benz");
benz.run();
Car bmw=SimpleFactory.getCar("bmw");
bmw.run();
}
}
工厂模式:
package factory.model;
public interface Car {
void run();
}
package factory.model;
public class Benz implements Car{
@Override
public void run() {
System.out.println("奔驰在跑");
}
}
package factory.model;
public class Bmw implements Car{
@Override
public void run() {
System.out.println("宝马在跑");
}
}
package designMode.factory;
import designMode.model.Car;
public interface Factory {
Car produceCar();
}
package designMode.factory;
import designMode.model.Benz;
import designMode.model.Car;
public class BenzFactory implements Factory{
@Override
public Car produceCar() {
System.out.println("工廠模式生产奔驰");
return new Benz();
}
}
package designMode.factory;
import designMode.model.Bmw;
import designMode.model.Car;
public class BmwFactory implements Factory{
@Override
public Car produceCar() {
System.out.println("工廠模式生产宝马");
return new Bmw();
}
}
package designMode.factory;
import designMode.model.Car;
public class FactoryValidation {
public static void main(String[] args) {
Factory benzFactory = new BenzFactory();
Car benz=benzFactory.produceCar();
benz.run();
Factory bmwFactory = new BmwFactory();
Car bmw=bmwFactory.produceCar();
bmw.run();
}
}