存在Shape,Color两个工厂
这两个工厂又继承抽象类AbstractFactory。
自上而下
先创建顶层抽象工厂:AbstractFactory.java,有两个抽象方法,传一个String参数,返回Shap/Color对象
public abstract class AbstractFactory {
abstract Shape getShape(String shape);
abstract Color getColor(String color);
}
然后创建ShapeFactory.java和ColorFactory.java,继承AbstractFactory.java。根据不同的传参返回不同的Shape/Color。
public class ShapeFactory extends AbstractFactory {
@Override
Shape getShape(String shape) {
switch (shape){
case "Circle":{
return new Circle();
}
case "Square":{
return new Square();
}
}
return null;
}
@Override
Color getColor(String color) {
return null;
}
}
public class ColorFactoyr extends AbstractFactory {
@Override
Shape getShape(String shape) {
return null;
}
@Override
Color getColor(String color) {
switch (color){
case "Red":{
return new Red();
}
case "Green":{
return new Green();
}
}
return null;
}
}
创建两个接口Shape.java和Color.java,给Shape接口一个draw()方法,给Color接口一个fill()方法
public interface Shape {
void draw();
}
public interface Color {
void fill();
}
创建Shape和Color的实现类
public class Square implements Shape {
@Override
public void draw() {
System.out.println("drawing square...");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("drawing circle....");
}
}
-------------------------------------------------------------------
public class Green implements Color{
@Override
public void fill() {
System.out.println("filling green...");
}
}
public class Red implements Color{
@Override
public void fill() {
System.out.println("filling red...");
}
}
这样就完成了抽象工厂模式,就是有一个抽象类用来生成工厂类,最后写一个测试方法验证下
public class AbstractFactoryTest {
public static void main(String[] args) {
AbstractFactory shapeFactory = new ShapeFactory();
Shape shape = shapeFactory.getShape("Circle");
shape.draw();
AbstractFactory colorFactory = new ColorFactoyr();
Color color = colorFactory.getColor("Red");
color.fill();
}
}