第三周作业
发布于: 2020 年 10 月 04 日
1 请在草稿纸上手写一个单例模式的实现代码。

单例模式
2代码编写

代码采用组合方式实现,Client为客户端调用类,IElement为公共抽象接口,Element为所有组件抽象父类,Container为可以容纳子控件的类,WinForm和Frame集成自Container,其他组件集成自Element

组合模式结构图
实现代码:
package test;import java.util.ArrayList;public class Client{  public static void main(String[] args)  {    IElement winform = new WinForm("WINDOW窗口");    winform.add(new Picture("LOGO图片"));    winform.add(new Button("登录"));    winform.add(new Button("注册"));        IElement frame = new Frame("FRAME1");    frame.add(new Lable("用户名"));    frame.add(new TextBox("文本框"));    frame.add(new Lable("密码"));    frame.add(new PasswordBox("密码框"));    frame.add(new CheckBox("复选框"));    frame.add(new TextBox("记住用户名"));    frame.add(new LinkLable("忘记密码"));    winform.add(frame);        winform.print();  }}//接口public interface IElement{  public void print();}//抽象父类abstract class Element implements IElement{  private String name;  private String text;  public Element(String name, String text)  {    this.name = name;    this.text = text;  }  public void print()  {    System.out.println(String.format("print %s(%s)\n", name, text));  }}//抽象容器类abstract class Container extends Element{  private ArrayList<IElement> fields=new ArrayList<IElement>();  public void add(IElement e)  {    fields.add(e);  }  public void print()  {    super.print();    for(IElement e:fields)    {      e.print();    }  }}//组件实现类,WinForm和Frame集成自Contriner容器类class WinForm extends Container{    public WinForm(String text)    {        super(WinForm.class.getSimpleName(), text);    }}class Picture extends Element{    public Picture(String text)    {        super(Picture.class.getSimpleName(), text);    }}class Button extends Element{    public Button(String text)    {        super(Button.class.getSimpleName(), text);    }}class Frame extends Container{    public Frame(String text)    {        super(Frame.class.getSimpleName(), text);    }}class Lable extends Element{    public Lable(String text)    {        super(Lable.class.getSimpleName(), text);    }}class TextBox extends Element{    public TextBox(String text)    {        super(TextBox.class.getSimpleName(), text);    }}class PasswordBox extends Element{    public PasswordBox(String text)    {        super(PasswordBox.class.getSimpleName(), text);    }}class CheckBox extends Element{    public CheckBox(String text)    {        super(CheckBox.class.getSimpleName(), text);    }}class TextBox extends Element{    public TextBox(String text)    {        super(TextBox.class.getSimpleName(), text);    }}class LinkLable extends Element{    public LinkLable(String text)    {        super(LinkLable.class.getSimpleName(), text);    }}
 划线
   评论
  复制
发布于: 2020 年 10 月 04 日 阅读数: 20
 
 熊桂平
  关注 
还未添加个人签名 2020.09.14 加入
还未添加个人简介
 
 
  
  
 
 
 
  
  
  
  
  
  
  
  
    
评论