1、创建图形、颜色接口类
Color.java
public interface Color {
void draw();
}
Shape.java
public interface Shape {
void draw();
}
2、实现图形类、颜色类接口
RedImpl.java
public class RedImpl implements Color {
@Override
public void draw() {
System.out.println("this is red color");
}
}
YellowImpl.java
public class YellowImpl implements Color {
@Override
public void draw() {
System.out.println("this is yellow color");
}
}
BlueImpl.java
public class BlueImpl implements Color {
@Override
public void draw() {
System.out.println("this is blue color");
}
}
图形类接口实现参见 上篇Blog《设计模式之工厂模式》
3、创建抽象类工厂 AbstractFactoryProduce.java
public abstract class AbstractFactoryProduce {
public abstract Shape getShape(String shape);
public abstract Color getColor(String color);
}
4、实现抽象类工厂
ShapeFactory.java
public class ShapeFactory extends AbstractFactoryProduce {
@Override
public Shape getShape(String shape) {
if(shape == null) {
return null;
}
if(shape.equalsIgnoreCase("circle")) {
return new CircleImpl();
}
if(shape.equalsIgnoreCase("square")) {
return new SquareImpl();
}
if(shape.equalsIgnoreCase("rectangle")) {
return new RectangleImpl();
}
return null;
}
@Override
public Color getColor(String color) {
// TODO Auto-generated method stub
return null;
}
}
ColorFactory.java
public class ColorFactory extends AbstractFactoryProduce {
@Override
public Color getColor(String color) {
if(color == null) {
return null;
}
if(color.equalsIgnoreCase("red")) {
return new RedImpl();
}
if(color.equalsIgnoreCase("yellow")) {
return new YellowImpl();
}
if(color.equalsIgnoreCase("blue")) {
return new BlueImpl();
}
return null;
}
@Override
public Shape getShape(String shape) {
// TODO Auto-generated method stub
return null;
}
}
5、创建工厂制造器类
FactoryProduce.java
public class FactoryProduce {
public static AbstractFactoryProduce getFactory(String factory) {
if(factory == null) {
return null;
}
if(factory.equalsIgnoreCase("shape")) {
return new ShapeFactory();
}
if(factory.equalsIgnoreCase("color")) {
return new ColorFactory();
}
return null;
}
}
6、调用测试
public class AbstractFactoryPatternDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
AbstractFactoryProduce shapeFatory = FactoryProduce.getFactory("shape");
AbstractFactoryProduce colorFatory = FactoryProduce.getFactory("color");
Shape circle = shapeFatory.getShape("circle");
circle.draw();
Shape square = shapeFatory.getShape("square");
square.draw();
Shape rectangle = shapeFatory.getShape("rectangle");
rectangle.draw();
Color redColor = colorFatory.getColor("red");
redColor.draw();
Color yellowColor = colorFatory.getColor("yellow");
yellowColor.draw();
Color blueColor = colorFatory.getColor("blue");
blueColor.draw();
}
}
测试结果