单例模式和组合模式实例
作者:L001
- 2020 年 6 月 24 日
本文字数:857 字
阅读完需:约 3 分钟
单例模式
请用组合设计模式编写程序,打印输出图 1 的窗口,窗口组件的树结构如图 2 所示,打印输出示例参考图
/** * 抽象基类 */public abstract class BaseCommpnt { protected String name; public BaseCommpnt(String name) { this.name = name; } public abstract void print();}
复制代码
容器类
public class Continer extends BaseCommpnt {public class Continer extends BaseCommpnt { private List<BaseCommpnt> subNodes = new ArrayList<>();
public Continer(String path) { super(path); } @Override public void print() { System.out.println("容器:"+super.name+""); for (BaseCommpnt subNode : subNodes) { subNode.print(); } } /** * 添加组件 * @param c */ public void addCommont(BaseCommpnt c){ subNodes.add(c); }}复制代码
具体组件类,可以再次继承实现具体类
public class Commpont extends BaseCommpnt { public Commpont(String name) { super(name); } @Override public void print() { System.out.println("组件:"+super.name+""); }}复制代码
调用类
public static void main(String[] args) {
Continer form = new Continer("Windows 窗口"); Commpont logo = new Commpont("LOGO图片"); Commpont loginButton = new Commpont("登陆"); Commpont regeistButton = new Commpont("注册"); form.addCommont(logo); form.addCommont(loginButton); form.addCommont(regeistButton);
Continer iframe= new Continer("FRAME1");
Continer textbox = new Continer("文本框"); Commpont userLabel = new Commpont("标签-用户名"); Commpont pwdLabel = new Commpont("标签-密码"); Commpont userInput = new Commpont("用户名-input"); Commpont pwdInput = new Commpont("密码-input");
textbox.addCommont(userLabel); textbox.addCommont(pwdLabel); textbox.addCommont(userInput); textbox.addCommont(pwdInput);
Commpont checkbox = new Commpont("checkbox"); Commpont label_1 = new Commpont("label"); iframe.addCommont(textbox); iframe.addCommont(checkbox); iframe.addCommont(label_1); form.addCommont(iframe);
form.print();
}复制代码
调用结果-
容器:Windows 窗口组件:LOGO图片组件:登陆组件:注册容器:FRAME1容器:文本框组件:标签-用户名组件:标签-密码组件:用户名-input组件:密码-input组件:checkbox组件:label复制代码
划线
评论
复制
发布于: 2020 年 06 月 24 日
L001
关注
还未添加个人签名 2018.04.28 加入
还未添加个人简介











评论