架构师训练营第三周作业
发布于: 2020 年 06 月 24 日
1.手写单例模式
注:单例的写法有很多种,大概我知道的就有七八种吧,但是考虑到线程安全和性能的,我觉得恶汉模式和双重检查、枚举较好。本次就写一个日常工作中常用的双重检查吧。
如下图所示:
 2.请用组合设计模式编写程序
public interface Element {
    void add(Element element);
    void remove(Element element);
    void display();}
public class Leaf implements Element{
    Leaf(String name){        this.name = name;    }
    private String name;    @Override    public void add(Element element) {
    }
    @Override    public void remove(Element element) {
    }
    @Override    public void display() {        System.out.println("print " + name);    }
    public String getName() {        return name;    }
    public void setName(String name) {        this.name = name;    }}
import java.util.ArrayList;import java.util.List;
public class Composite implements Element{
    Composite(String name){        this.name = name;    }
    List<Element> partLists = new ArrayList<Element>(16);
    private String name;
    @Override    public void add(Element element) {        partLists.add(element);    }
    @Override    public void remove(Element element) {        partLists.remove(element);    }
    @Override    public void display() {        System.out.println("print " + name);        for(Element e : partLists){            e.display();        }    }
    public String getName() {        return name;    }
    public void setName(String name) {        this.name = name;    }}
public class Main {
    public static void main(String[] args) {        Element winForm = new Composite("WinForm(WINDOW窗口)");        Element picture = new Leaf("Picture(LOGO图片)");        Element button1 = new Leaf("Button(登录)");        Element button2 = new Leaf("Button(注册)");        winForm.add(picture);        winForm.add(button1);        winForm.add(button2);
        Element frame = new Composite("Frame(FRAME1)");        Element label1 = new Leaf("Lable(用户名)");        Element textbox = new Leaf("TextBox(文本框)");        Element label2 = new Leaf("Label(密码)");        Element passwordBox = new Leaf("PasswordBox(密码框)");        Element checkBox = new Leaf("CheckBox(复选框)");        Element textbox2 = new Leaf("TextBox(记住用户名)");        Element linkLabel = new Leaf("LinkLable(忘记密码)");        frame.add(label1);        frame.add(textbox);        frame.add(label2);        frame.add(passwordBox);        frame.add(checkBox);        frame.add(textbox2);        frame.add(linkLabel);
        winForm.add(frame);        winForm.display();    }}
复制代码
 划线
评论
复制
发布于: 2020 年 06 月 24 日阅读数: 51
路人
关注
还未添加个人签名 2018.07.26 加入
还未添加个人简介











    
评论