抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。
/**
* 创建一个接口
* @author fan
*
*/
public interface Car {
public void driver();
}
/**
* 接口实现类
* @author fan
*
*/
public class Bc implements Car{
@Override
public void driver() {
// TODO Auto-generated method stub
System.out.println("driver Bc");
}
/**
* 接口实现类
* @author fan
*
*/
public class Bmw implements Car{
@Override
public void driver() {
// TODO Auto-generated method stub
System.out.println("driver bmw");
}
}
public interface Color {
public void print();
}
public class Green implements Color {
@Override
public void print() {
// TODO Auto-generated method stub
System.out.println("green");
}
}
public class Red implements Color {
@Override
public void print() {
// TODO Auto-generated method stub
System.out.println("red");
}
}
/**
* 创建抽象工厂
* @author fan
*
*/
public abstract class AbstractFactory {
abstract Color GetColors(String color);
abstract Car GetCar(String car);
}
/**
* 创建工厂
* @author fan
*
*/
public class ColorFactory extends AbstractFactory{
@Override
public Color GetColors(String color) {
// TODO Auto-generated method stub
if (color == null) {
return null;
}
if (color.equalsIgnoreCase("GREEN")) {
return new Green();
} else if (color.equalsIgnoreCase("RED")) {
return new Red();
}
return null;
}
@Override
Car GetCar(String car) {
// TODO Auto-generated method stub
return null;
}
}
/**
* 创建工厂
* @author fan
*
*/
public class CarFactory extends AbstractFactory{
@Override
Color GetColors(String color) {
// TODO Auto-generated method stub
return null;
}
@Override
Car GetCar(String car) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (car == null) {
return null;
}
if (car.equalsIgnoreCase("BMW")) {
return new Bmw();
} else if (car.equalsIgnoreCase("BC")) {
return new Bc();
}
return null;
}
}
/**
* 工厂生成器
* @author fan
*
*/
public class FactoryProducer {
public static AbstractFactory getFactory(String choice) {
if (choice.equalsIgnoreCase("COLOR")) {
return new ColorFactory();
} else if (choice.equalsIgnoreCase("CAR")) {
return new CarFactory();
}
// TODO Auto-generated method stub
return null;
}
}
public class Test {
public static void main(String[] args) {
AbstractFactory carFactory = FactoryProducer.getFactory("CAR");
AbstractFactory colorfactory = FactoryProducer.getFactory("COLOR");
Car bwm = carFactory.GetCar("bmw");
Car bc = carFactory.GetCar("bc");
bwm.driver();
bc.driver();
Color green = colorfactory.GetColors("GREEN");
Color red = colorfactory.GetColors("RED");
green.print();
red.print();
}
}