抽象工厂模式 AbstractFactory

Abstract Factory模式中将具体的Product封装在具体Factory实现中,而客户仍只要面对Factory与Product的抽象介面,避免依赖于具 体的Factory与Product,由于Factory封装了所必须的Product,所以要更换掉所有的元件,只要简单的抽换掉Factory就可以 了,不用修改客户端的程式。

/**
 * @author Jerval
 * @date 2011-4-23
 */
public interface IButton {

	public void drawButton();
}

/**
 * @author Jerval
 * @date 2011-4-23
 */
public interface ILabel {
	
	public void drawLabel();
}
/**
 * @author Jerval
 * @date 2011-4-23
 */
public class XpButton implements IButton {

	@Override
	public void drawButton() {
		System.out.println("draw xp button....");
	}

}

/**
 * @author Jerval
 * @date 2011-4-23
 */
public class XpLabel implements ILabel {

	@Override
	public void drawLabel() {
		System.out.println("draw xp label...");
	}

}

/**
 * @author Jerval
 * @date 2011-4-23
 */
public class VistaButton implements IButton {

	@Override
	public void drawButton() {
		System.out.println("draw vista button....");
	}

}

/**
 * @author Jerval
 * @date 2011-4-23
 */
public class VistaLabel implements ILabel {

	@Override
	public void drawLabel() {
		System.out.println("draw vista label...");
	}

}


/**
 * @author Jerval
 * @date 2011-4-23
 */
public interface IStyleFactory {

	public IButton getButton();
	public ILabel getlILabel();
}

/**
 * @author Jerval
 * @date 2011-4-23
 */
public class XpStyleFactory implements IStyleFactory{

	@Override
	public IButton getButton() {
		return new XpButton();
	}

	@Override
	public ILabel getlILabel() {
		return new XpLabel();
	}

}
/**
 * @author Jerval
 * @date 2011-4-23
 */
public class VistaStyleFactory implements IStyleFactory{

	@Override
	public IButton getButton() {
		return new VistaButton();
	}

	@Override
	public ILabel getlILabel() {
		return new VistaLabel();
	}

}


/**
 * @author Jerval
 * @date 2011-4-23
 */
public class CustomMsgBox {

	private IButton button;
	private ILabel label;

	public CustomMsgBox(IStyleFactory styleFactory) {
		setStyleFactory(styleFactory);
	}

	// 客户端依赖于抽象工厂,更换工厂不需要改动客户端
	public void setStyleFactory(IStyleFactory styleFactory) {
		setButton(styleFactory.getButton());
		setLabel(styleFactory.getlILabel());
	}

	// 依赖抽象,改变了元件实例客户端代码也不用更改
	public void setButton(IButton button) {
		this.button = button;
	}

	public void setLabel(ILabel label) {
		this.label = label;
	}

	public void show() {
		drawCustomMsgBox();
		button.drawButton();
		label.drawLabel();
	}

	private void drawCustomMsgBox() {
		System.out.println("draw CustomMsgBox...");
	}
}

/**
 * @author Jerval
 * @date 2011-4-23
 */
public class MainClass {

	public static void main(String[] args) {
		//show xp style msgBox
		CustomMsgBox xpStyleMsgBox = new CustomMsgBox(new XpStyleFactory());
		xpStyleMsgBox.show();
		//show vista style msgBox
		CustomMsgBox vistaStyleMsgBox = new CustomMsgBox(new VistaStyleFactory());
		vistaStyleMsgBox.show();
	}
}
 

猜你喜欢

转载自jerval.iteye.com/blog/1013632
今日推荐