首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

抽象工场模式 AbstractFactory

2012-09-09 
抽象工厂模式 AbstractFactoryAbstract Factory模式中将具体的Product封装在具体Factory实现中,而客户仍只

抽象工厂模式 AbstractFactory

抽象工场模式 AbstractFactoryAbstract 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 {@Overridepublic void drawButton() {System.out.println("draw xp button....");}}/** * @author Jerval * @date 2011-4-23 */public class XpLabel implements ILabel {@Overridepublic void drawLabel() {System.out.println("draw xp label...");}}/** * @author Jerval * @date 2011-4-23 */public class VistaButton implements IButton {@Overridepublic void drawButton() {System.out.println("draw vista button....");}}/** * @author Jerval * @date 2011-4-23 */public class VistaLabel implements ILabel {@Overridepublic 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{@Overridepublic IButton getButton() {return new XpButton();}@Overridepublic ILabel getlILabel() {return new XpLabel();}}/** * @author Jerval * @date 2011-4-23 */public class VistaStyleFactory implements IStyleFactory{@Overridepublic IButton getButton() {return new VistaButton();}@Overridepublic 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 msgBoxCustomMsgBox xpStyleMsgBox = new CustomMsgBox(new XpStyleFactory());xpStyleMsgBox.show();//show vista style msgBoxCustomMsgBox vistaStyleMsgBox = new CustomMsgBox(new VistaStyleFactory());vistaStyleMsgBox.show();}}
?

热点排行