设计模式 - 单例 & 组合

发布于: 41 分钟前

一、手写单例模式

上饿汉、下懒汉

二、组合模式打印窗口组件

类图如下

详细代码

1、打印接口

public interface IPrintable {
void print();
}

2、组件父类,实现打印接口

public class Component implements IPrintable {
public Component(String name){
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void print() {
String componentName = getClass().getSimpleName();
System.out.println(String.format("print %s(%s)", componentName, name));
}
}

3、容器父类,继承组件类,重写打印方法

public class Container extends Component {
public Container(String name){
super(name);
}
private List<Component> childList;
public void addChild(Component component){
if(childList == null){
childList = new ArrayList<>();
}
childList.add(component);
}
@Override
public void print() {
super.print();
if(childList == null || childList.size() == 0){
return;
}
childList.stream().forEach(component -> {
component.print();
});
}
}

4、各种组件的实现

WinForm、Frame继承容器类Container,Label、Button、TextBox等继承组件类Component

public class WinForm extends Container {
public WinForm(String name) {
super(name);
}
}
public class Frame extends Container {
public Frame(String name) {
super(name);
}
}
public class Button extends Component {
public Button(String name) {
super(name);
}
}
public class Label extends Component {
public Label(String name) {
super(name);
}
}
public class CheckBox extends Component {
public CheckBox(String name) {
super(name);
}
}
public class LinkLabel extends Component {
public LinkLabel(String name) {
super(name);
}
}
public class PasswordBox extends Component {
public PasswordBox(String name) {
super(name);
}
}
public class Picture extends Component {
public Picture(String name) {
super(name);
}
}
public class TextBox extends Component {
public TextBox(String name) {
super(name);
}
}

5、测试类

public static void main(String[] args){
WinForm winForm = new WinForm("WINDOW窗口");
winForm.addChild(new Picture("LOGO图片"));
winForm.addChild(new Button("登陆"));
winForm.addChild(new Button("注册"));
Frame frame1 = new Frame("FRAME1");
frame1.addChild(new Label("用户名"));
frame1.addChild(new TextBox("文本框"));
frame1.addChild(new TextBox("密码"));
frame1.addChild(new PasswordBox("密码框"));
frame1.addChild(new CheckBox("复选框"));
frame1.addChild(new TextBox("记住用户名"));
frame1.addChild(new LinkLabel("忘记密码"));
winForm.addChild(frame1);
winForm.print();
}

测试结果

print WinForm(WINDOW窗口)
print Picture(LOGO图片)
print Button(登陆)
print Button(注册)
print Frame(FRAME1)
print Label(用户名)
print TextBox(文本框)
print TextBox(密码)
print PasswordBox(密码框)
print CheckBox(复选框)
print TextBox(记住用户名)
print LinkLabel(忘记密码)

发布于: 41 分钟前 阅读数: 2
用户头像

Z冰红茶

关注

还未添加个人签名 2018.09.17 加入

还未添加个人简介

评论

发布
暂无评论
设计模式-单例&组合