抽象工厂模式可以向客户端提供一个接口,使得客户端在不必指定产品的具体类型的情况下,创建多个产品族的产品对象。
类图如下:
一个例子:由于业务需求,我公司引进了一个使用机器绘图,可以很方便绘制不同的几何形状,如圆形,方形和三角形。但是有时还得需要手动绘图,每个几何图形都要有画图draw()和擦去erase()两个方法,请使用抽象工厂来解决此问题
先实现定义抽象产品
public interface Shape {
public void draw();
public void erase();
}
public interface Circle extends Shape {
}
public interface Square extends Shape {
}
public interface Triangle extends Shape {
}
再定义手写版 的具体产品:
public class HandCircle implements Circle {
public void draw() {
System.out.println("HandCircle.draw()");
}
public void erase() {
System.out.println("HandCircle.erase()");
}
}
public class HandSquare implements Square {
public void draw() {
System.out.println("HandSquare.draw()");
}
public void erase() {
System.out.println("HandSquare.erase()");
}
}
public class HandTriangle implements Triangle {
public void draw() {
System.out.println("HandTriangle.draw()");
}
public void erase() {
System.out.println("HandTriangle.erase()");
}
}
再定义机器制造的具体产品:
public class MachineCircle implements Circle {
public void draw() {
System.out.println("MachineCircle.draw()");
}
public void erase() {
System.out.println("MachineCircle.erase()");
}
}
public class MachineSquare implements Square {
public void draw() {
System.out.println("MahchineSquare.draw()");
}
public void erase() {
System.out.println("MahchineSquare.erase()");
}
}
public class MachineTriangle implements Triangle {
public void draw() {
System.out.println("MachineTriangle.draw()");
}
public void erase() {
System.out.println("MachineTriangle.erase()");
}
}
再定义抽象工厂,实现了这个接口的类会创建三个不同等级的产品。
public interface ArtTracer {
public Circle createCircle();
public Square createSquare();
public Triangle createTriangle();
}
具体工厂:
//手写版的工厂
public class HandTracer implements ArtTracer {
public Circle createCircle() {
return new HandCircle();
}
public Square createSquare() {
return new HandSquare();
}
public Triangle createTriangle() {
return new HandTriangle();
}
}
//机器制造的工厂
public class MachineTracer implements ArtTracer {
public Circle createCircle() {
return new MachineCircle();
}
public Square createSquare() {
return new MachineSquare();
}
public Triangle createTriangle() {
return new MachineTriangle();
}
}
最后编写客户端进行测试:
public class Client {
public static void main(String[] args) {
ArtTracer artTracer = new HandTracer();
artTracer.createCircle().draw();
artTracer.createCircle().erase();
artTracer.createSquare().draw();
artTracer.createSquare().erase();
artTracer.createTriangle().draw();
artTracer.createTriangle().erase();
System.out.println("--------------------------");
artTracer = new MachineTracer();
artTracer.createCircle().draw();
artTracer.createCircle().erase();
artTracer.createSquare().draw();
artTracer.createSquare().erase();
artTracer.createTriangle().draw();
artTracer.createTriangle().erase();
}
}