利用组合设计模式编写一个界面打印
发布于: 2020 年 06 月 22 日

要求:

利用组合设计模式类图如下:

把ui组件分为Container容器和Component组件两个类,容器可以增加子组件或则容器,两个类都实现Printer接口,Containter使用组合设计模式有一个私有变量List<Printer>,来实现组件遍历打印功能代码如下
Printer接口
public interface Printer{ /** *打印组件信息 */ public void print();}
Container类
public class Container implements Printer { private List<Printer> list = new ArrayList<Printer>(); private String name; public Container(String name) { this.name = name; } @Override public void print() { System.out.println("print " + this.getClass().getSimpleName() + "(" + name + ")"); if (list != null && list.size() > 0) { for (Printer printer : list) { printer.print(); } } } public void addChild(Printer printer) { if (null == list) { list = new ArrayList<Printer>(); } list.add(printer); }}
Window类
public class Window extends Container { public Window(String name) { super(name); }}
Component类
public class Component implements Printer { private String name; public Component(String name){ this.name = name; } @Override public void print() { System.out.println("print " + this.getClass().getSimpleName() + "(" + name + ")"); }}
Button类继承Component
public class Button extends Component { public Button(String name) { super(name); }}
测试类:
public class MainTest { public static void main(String[] args){ Window window = new Window("WINDOW窗口"); Picture picture= new Picture("LOGO图片"); window.addChild(picture); Button logonButton = new Button("登录"); window.addChild(logonButton); Button registerButton = new Button("注册"); window.addChild(registerButton); Frame frame = new Frame("FRAME1"); window.addChild(frame); Label userNameLabel = new Label("用户名"); frame.addChild(userNameLabel); TextBox userNameText = new TextBox("文本框"); frame.addChild(userNameText); Label passwordLabel = new Label("密码"); frame.addChild(userNameLabel); PasswordBox passwordText = new PasswordBox("密码框"); frame.addChild(passwordText); CheckBox checkBox =new CheckBox("复选框"); frame.addChild(checkBox); TextBox textBox = new TextBox("记住用户名"); frame.addChild(textBox); LinkLabel linkLabel = new LinkLabel("忘记密码"); frame.addChild(linkLabel); window.print(); }}
测试输出:

总结:
组合模式一般用于将对象表达成树状的层次结构,让客服端很方便的遍历这个树状结构,树状中的叶子节点和枝节点能很方便扩展
划线
评论
复制
发布于: 2020 年 06 月 22 日阅读数: 61

elfkingw
关注
还未添加个人签名 2018.02.04 加入
还未添加个人简介
评论