第三周·作业一·命题作业

发布于: 2020 年 06 月 24 日
第三周·作业一·命题作业

手写单例模式

单例模式三个主要特点:

1、构造方法私有化;

2、实例化的变量引用私有化;

3、获取实例的方法共有。

组合模式练习

如下图实现窗口打印

源代码

@Data
abstract class Component {
protected String type;
protected String name;
public Component(String type,String name) {
this.type = type;
this.name = name;
}
public abstract void add(Component component) throws Exception;
public abstract void remove(Component component) throws Exception;
public void draw(){
System.out.println(String.format("print %s(%s)", this.getType(), this.getName()));
}
}

class Control extends Component {
public Control(String type,String name) {
super(type,name);
}
@Override
public void add(Component component) throws Exception {
throw new Exception("不能在Control中新增Control");
}
@Override
public void remove(Component component) throws Exception {
throw new Exception("不能删除下级Control");
}
}

public class Frame extends Component {
private List<Component> componentList;
public Frame(String type, String name) {
super(type, name);
componentList = new ArrayList<>();
}
@Override
public void add(Component component) throws Exception {
if (componentList == null) {
componentList = new ArrayList<>();
}
componentList.add(component);
}
@Override
public void remove(Component component) throws Exception {
if (componentList == null) {
return;
}
componentList.remove(component);
}
@Override
public void draw() {
super.draw();
for (Component component : componentList) {
component.draw();
}
}
}

public class WindowsManager {
Frame window = new Frame("Window", "WINDOW窗口");
public WindowsManager() throws Exception {
window.add(new Control("Picture", "LOGO图片"));
window.add(new Control("Button", "登录"));
window.add(new Control("Button", "注册"));
Frame fram = new Frame("Frame", "FRAME1");
window.add(fram);
fram.add(new Control("Label", "用户名"));
fram.add(new Control("TextBox", "文本框"));
fram.add(new Control("Label", "密码"));
fram.add(new Control("PasswordBox", "密码框"));
fram.add(new Control("CheckBox", "复选框"));
fram.add(new Control("TextBox", "记住用户名"));
fram.add(new Control("LinkLable", "忘记密码"));
}
public void draw(){
this.window.draw();
}
}

执行结果

用户头像

刘璐

关注

还未添加个人签名 2018.03.29 加入

还未添加个人简介

评论

发布
暂无评论
第三周·作业一·命题作业