抽象工厂模式可以分为两个继承层次来说
一个是工厂类的继承层次 如
/**
* 分辨率工厂
* @author xuly
*
*/
public interface ResolutionFactory {
DisplayDriver createDisplayDriver();
PrintDriver createPrintDriver();
}
/**
* 高分辨率工厂
* @author xuly
*
*/
public class HighResFactory implements ResolutionFactory {
public DisplayDriver createDisplayDriver() {
return new HighDisplayDriver();
}
public PrintDriver createPrintDriver() {
return new HighPrintDriver();
}
}
/**
* 低分辨率工厂
* @author xuly
*
*/
public class LowResFactory implements ResolutionFactory {
public DisplayDriver createDisplayDriver() {
return new LowDisplayDriver();
}
public PrintDriver createPrintDriver() {
return new LowPrintDriver();
}
}
因为要生产多个产品系列 所以要多个工厂,一个工厂负责一类产品的生产
为什么叫抽象工厂呢?
先看类LowResFactory, 如果不实现ResolutionFactory 接口的话,LowResFactory就是一个简单的工厂类,但是因为要创建的产品是分系列的,因此我们抽象出一个ResolutionFactory 接口,然后分别实现,工厂的层次是受产品的层次控制的,如果有3个产品系列那么相应的就应该有3个工厂
另一个是产品的继承层次 如
//显示驱动
public interface DisplayDriver {
public void draw();
}
public class HighDisplayDriver implements DisplayDriver {
public void draw() {
System.out.println( "高分辨率显示图形." );
}
}
public class LowDisplayDriver implements DisplayDriver {
public void draw() {
System.out.println( "低分辨率显示图形." );
}
}
//打印驱动
public interface PrintDriver {
void print();
}
public class HighPrintDriver implements PrintDriver {
public void print() {
System.out.println( "高分辨率打印图形." );
}
}
public class LowPrintDriver implements PrintDriver {
public void print() {
System.out.println( "低分辨率打印图形." );
}
}
没什么好说的 就是简单的继承
Client
public class Client2 {
private ResolutionFactory resFactory;
public Client2(ResolutionFactory resFactory){
this.resFactory = resFactory;
}
public void doDraw(){
resFactory.createDisplayDriver().draw();
}
public void doPrint(){
resFactory.createPrintDriver().print();
}
//调用
public static void main(String[] args) {
Client2 control = new Client2(new HighResFactory());
control.doDraw();
control.doPrint();
}
}