简单工厂模式
简单工厂的定义:提供一个创建对象实例的功能,而无须关心其具体实现。被创建实例的类型可以是接口、抽象类,也可以是具体的类
实现汽车接口
public interface Car {
String getName();
}
奔驰类
public class Benz implements Car {
@Override
public String getName() {
return "Benz";
}
}
宝马类
public class BMW implements Car {
@Override
public String getName() {
return "BMW";
}
}
简单工厂,既能生产宝马又能生产奔驰
public class simpleFactory {
public Car getCar(String name) {
if ( name.equals("BMW")) {
return new BMW();
} else if ( name.equals("Benz")) {
return new Benz();
} else {
System.out.println("no");
return null;
}
}
}
测试类
public class SimpleFactoryTest {
public static void main(String[] args) {
simpleFactory simple = new simpleFactory();
Car car = simple.getCar("BMW");
System.out.println(car.getName());
}
}
工厂方法
工厂接口
public interface Factory {
Car getCar();
}
奔驰工厂
public class BenzFactory implements Factory {
@Override
public Car getCar() {
return new Benz();
}
}
宝马工厂
public class BMWFactory implements Factory {
@Override
public Car getCar() {
return new BMW();
}
}
测试类
public static void main(String[] args) {
Factory bmwFactory = new BMWFactory();
System.out.println(bmwFactory.getCar().getName());
Factory benzFactory = new BenzFactory();
System.out.println(benzFactory.getCar().getName());
}
抽象工厂
抽象工厂
public abstract class AbastractFactory {
protected abstract Car getCar();
public Car getCar(String name) {
if ( "BMW".equalsIgnoreCase(name)) {
return new BMWFactory().getCar();
} else if ( "Benz".equalsIgnoreCase(name) ) {
return new BenzFactory().getCar();
} else {
return null;
}
}
}