Java设计模式-----Abstract Factory抽象工厂模式

源自:http://www.blogjava.net/flustar/archive/2007/11/28/abstractFactory.html

Abstract Factory抽象工厂模式:

为创建一组相关或相互依赖的对象提供一个接口,而且无需指定它们的具体类。大致意思是说:我们在创建这些对象的时候,并不需要指定它们的具体类,这些具体类的对象是由工厂对象负责实例化的。

例子:

public abstract class DisplayDriver {
}

public abstract class PrintDriver {
}

public class HRDD extends DisplayDriver {

	public HRDD() {
		System.out.println("使用高端机的显示驱动程序");
	}
}

public class HRPD extends PrintDriver {

	public HRPD() {
		System.out.println("使用高端机的打印驱动程序");
	}
}

public class LRDD extends DisplayDriver {
	
	public LRDD() {
		System.out.println("使用低端机的显示驱动程序");
	}
}

public class LRPD extends PrintDriver {

	public LRPD() {
        System.out.println("使用低端机的打印驱动程序");
    }
}

public abstract class ResFactory {

	abstract public DisplayDriver getDisplayDrvr();

    abstract public PrintDriver getPrintDrvr();
}

public class HighResFact extends ResFactory {

	public DisplayDriver getDisplayDrvr() {
		return new HRDD();
	}

	public PrintDriver getPrintDrvr() {
		return new HRPD();
	}
}

public class LowResFact extends ResFactory {

	public DisplayDriver getDisplayDrvr() {
		return new LRDD();
	}

	public PrintDriver getPrintDrvr() {
		return new LRPD();
	}
}

public class ApControl {
	
	public static ResFactory getResFactory(ResFactory factory) {
		return factory;
	}

	public static void main(String[] args) {

		ResFactory highResFact = ApControl.getResFactory(new HighResFact());
		highResFact.getDisplayDrvr();
		highResFact.getPrintDrvr();
		ResFactory lowResFact = ApControl.getResFactory(new LowResFact());
		lowResFact.getDisplayDrvr();
		lowResFact.getPrintDrvr();
	}
}

你可能感兴趣的:(Java相关)