抽象工厂中 接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。 在简单工厂中,我们需要一辆车就用CarFactory创建一个,但是我们需要一辆红色轿车,这时候就需要里一个油漆工厂来加工颜色。去车厂买辆车,再去油漆厂喷漆,如果这样的话下次我们如果想加一个骚气的跑马灯就还要去灯厂,这样跑来跑去好麻烦,有没有一个地方都能做就不用来回跑了?4s店
1、定义Car接口、Color接口
public interface Car {
/**
* 加油门
*/
public void run();
/**
* 刹车
*/
public void stop();
}
public interface Color {
/**
* 喷漆
*/
public void fill();
}
2、定义Car和Color的实现类
public class Taxi implements Car {
@Override
public void run() {
System.out.println("打表计价中");
}
@Override
public void stop() {
System.out.println("本次费用xx元");
}
}
public class Bus implements Car {
@Override
public void run() {
System.out.println("车辆行人请注意");
}
@Override
public void stop() {
System.out.println("xxx站到了");
}
}
public class Sedan implements Car {
@Override
public void run() {
System.out.println("一路向西去大理");
}
@Override
public void stop() {
System.out.println("抛锚了...");
}
}
public class Red implements Color {
@Override
public void fill() {
System.out.println("喷上骚红");
}
}
public class Green implements Color {
@Override
public void fill() {
System.out.println("来点大自然的颜色");
}
}
public class Black implements Color {
@Override
public void fill() {
System.out.println("死亡的气息");
}
}
3、为Car和Color创建抽象类来获取工厂
public abstract class AbstractFactory {
public abstract Car getCar(String type);
public abstract Color getColor(String color);
}
4、创建AbstractFactory的扩展类
public class OilPaintFactory extends AbstractFactory {
@Override
public Car getCar(String type) {
return null;
}
@Override
public Color getColor(String type) {
if (type == null) {
return null;
}
if (type.equalsIgnoreCase("red")) {
return new Red();
}
if (type.equalsIgnoreCase("black")) {
return new Black();
}
if (type.equalsIgnoreCase("green")) {
return new Green();
}
return null;
}
}
public class CarFactory extends AbstractFactory {
@Override
public Car getCar(String type) {
if (type == null) {
return null;
}
if (type.equalsIgnoreCase("taxi")) {
return new Taxi();
}
if (type.equalsIgnoreCase("bus")) {
return new Bus();
}
if (type.equalsIgnoreCase("sedan")) {
return new Sedan();
}
return null;
}
@Override
public Color getColor(String color) {
return null;
}
}
5、创建工厂的生产类,用于生产工厂
public class FourSonFactoryProducer {
public static AbstractFactory getFactory(String choice) {
if (choice == null) {
return null;
}
if (choice.equalsIgnoreCase("color")) {
return new OilPaintFactory();
}
if (choice.equalsIgnoreCase("car")) {
return new CarFactory();
}
return null;
}
}
6、使用FourSonFactoryProducer获取工厂,根据不同类型获取对象
public class AbstractFactoryPatternTest {
public static void main(String[] args) {
//4s店选配置
AbstractFactory car = FourSonFactoryProducer.getFactory("car");
AbstractFactory color = FourSonFactoryProducer.getFactory("color");
//选一辆跑车
Car sedan = car.getCar("sedan");
//选个骚红
Color red = color.getColor("red");
//开着骚红的跑车
red.fill();
sedan.run();
sedan.stop();
}
}
7、输出结果
喷上骚红
一路向西去大理
抛锚了...
Process finished with exit code 0