作业 - 组合模式和单例模式
发布于: 2020 年 06 月 24 日
作业-组合模式和单例模式
1、组合模式的代码:
【MAIN入口】
package com.study;public class Main { public static void main(String[] args) { // write your code here System.out.println("BEGIN DRAWING!"); UIElement rootnode=new UINode("WinForm","windown 窗口"); UIElement picture=new UILeaf("Picture","LOGO 图片"); UIElement button1=new UILeaf("Button","注册"); UIElement button2=new UILeaf("Button","登录"); rootnode.add(picture); rootnode.add(button1); rootnode.add(button2); UIElement frame=new UINode("Frame","Frame1"); UIElement lable1=new UILeaf("Lable","用户名"); UIElement textbox1=new UILeaf("TextBox","文本框"); UIElement lable2=new UILeaf("Lable","密码"); UIElement passwdbox=new UILeaf("PasswdBox","密码框"); UIElement checkbox=new UILeaf("CheckBox","复选框"); UIElement textbox2=new UILeaf("TextBox","记住用户名"); UIElement linklable=new UILeaf("LinkLable","忘记密码"); frame.add(lable1); frame.add(textbox1); frame.add(lable2); frame.add(passwdbox); frame.add(checkbox); frame.add(textbox2); frame.add(linklable); rootnode.add(frame); rootnode.draw(1); System.out.println("END DRAWING!"); }}
【接口定义】
package com.study;public interface UIElement { public void draw(int depth); public void add(UIElement e);}
【NODE节点类】
package com.study;import java.util.ArrayList;public class UINode implements UIElement { private String strNodeType; private String strNodeName; private ArrayList<UIElement> uiElementList=new ArrayList<UIElement>(); public UINode(String strNodeType,String strNodeName) { this.strNodeType=strNodeType; this.strNodeName=strNodeName; } public void add(UIElement uiElement) { this.uiElementList.add(uiElement); } public void remove(UIElement uiElement) { this.uiElementList.remove(uiElement); } @Override public void draw(int depth) { for(int i=0;i<depth;i++) { System.out.print("-"); } System.out.println("【Node】:"+this.strNodeType+" "+this.strNodeName); for(UIElement uiElement:uiElementList) { uiElement.draw(depth+1); } }}
【Leaf节点类】
package com.study;public class UILeaf implements UIElement { private String strLeafType; private String strLeafName; public UILeaf(String strLeafType, String strLeafName) { this.strLeafType=strLeafType; this.strLeafName=strLeafName; } @Override public void draw(int depth) { for(int i=0;i<depth;i++) { System.out.print("-"); } System.out.println("【Leaf】:"+this.strLeafType+" "+this.strLeafName); } @Override public void add(UIElement e) { }}
[输出结果]:
2、单例
划线
评论
复制
发布于: 2020 年 06 月 24 日阅读数: 48
蒜泥精英
关注
还未添加个人签名 2018.09.19 加入
还未添加个人简介
评论