//Main.java
//抽象工厂模式Abstract Factory Pattern属于创建型模式的一种
//简单对比工厂模式,实际上相当于多加了"生产工厂"这一步
//比如circle产品,先构建生产形状的工厂,再让该工厂去生产circle
interface Shape{
}
class Rectangle implements Shape{
public Rectangle(){
System.out.println("New Rectangle");
}
}
class Square implements Shape{
public Square(){
System.out.println("New Square");
}
}
class Circle implements Shape{
public Circle(){
System.out.println("New Circle");
}
}
interface Color{
}
class Red implements Color{
public Red(){
System.out.println("New Red");
}
}
class Green implements Color{
public Green(){
System.out.println("New Green");
}
}
class Blue implements Color{
public Blue(){
System.out.println("New Blue");
}
}
abstract class AbstractFactory{
abstract Shape newShape(String shape);
abstract Color newColor(String color);
}
class ShapeFactory extends AbstractFactory{
public Shape newShape(String shapeType){
if(shapeType==null)return null;
if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}
if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
}
return null;
}
public Color newColor(String colorType){
return null;
}
}
class ColorFactory extends AbstractFactory{
public Shape newShape(String shapeType){
return null;
}
public Color newColor(String colorType){
if(colorType==null)return null;
if(colorType.equalsIgnoreCase("RED")){
return new Red();
}
if(colorType.equalsIgnoreCase("GREEN")){
return new Green();
}
if(colorType.equalsIgnoreCase("BLUE")){
return new Blue();
}
return null;
}
}
class FactoryFactory{
public static AbstractFactory getFactory(String factoryType){
if(factoryType.equalsIgnoreCase("SHAPE")){
return new ShapeFactory();
}
if(factoryType.equalsIgnoreCase("COLOR")){
return new ColorFactory();
}
return null;
}
}
public class Main{
public static void main(String[] args){
AbstractFactory shapeFactory=FactoryFactory.getFactory("shape");
AbstractFactory colorFactory=FactoryFactory.getFactory("color");
Shape shape1=shapeFactory.newShape("rectangle");
Shape shape2=shapeFactory.newShape("Square");
Shape shape3=shapeFactory.newShape("circle");
Color color1=colorFactory.newColor("red");
Color color2=colorFactory.newColor("green");
Color color3=colorFactory.newColor("blue");
}
}