第三周 - 作业
单例模式手写:
组合模式代码:
package designpattern;
import java.util.ArrayList;
import java.util.List;
abstract class Component {
protected String text;
public Component(String text) {
this.text = text;
}
public String getText() {
return text;
}
public abstract void print();
}
public class WinForm extends Component {
public WinForm(String text) {
super(text);
}
private List<Component> subNodes = new ArrayList<>();
@Override
public void print() {
System.out.println("print WinForm(" + text + ")");
for (Component node : subNodes) {
node.print();
}
}
public void addSubNode(Component component) {
subNodes.add(component);
}
public static void main(String[] args) {
WinForm wf = new WinForm("WINDOW窗口");
Picture p1 = new Picture("LOGO图片");
Button b1 = new Button("登录");
Button b2 = new Button("注册");
wf.addSubNode(p1); wf.addSubNode(b1); wf.addSubNode(b2);
Frame f1 = new Frame("FRAME1");
Lable l1 = new Lable("用户名");
TextBox tb1 = new TextBox("文本框");
Lable l2 = new Lable("密码");
PasswordBox pb1 = new PasswordBox("密码框");
CheckBox cb1 = new CheckBox("复选框");
TextBox tb2 = new TextBox("记住用户名");
LinkLabel ll1 = new LinkLabel("忘记密码");
f1.addSubNode(l1); f1.addSubNode(tb1);f1.addSubNode(l2);f1.addSubNode(pb1);
f1.addSubNode(cb1); f1.addSubNode(tb2); f1.addSubNode(ll1);
wf.addSubNode(f1);
wf.print();
}
}
class Picture extends Component {
public Picture(String text) {
super(text);
}
@Override
public void print() {
System.out.println("print Picture(" + text + ")");
}
}
class Button extends Component {
public Button(String text) {
super(text);
}
@Override
public void print() {
System.out.println("print Button(" + text + ")");
}
}
class Frame extends Component {
public Frame(String text) {
super(text);
}
private List<Component> subNodes = new ArrayList<>();
@Override
public void print() {
System.out.println("print Frame(" + text + ")");
for (Component node : subNodes) {
node.print();
}
}
public void addSubNode(Component component) {
subNodes.add(component);
}
}
class Lable extends Component {
public Lable(String text) {
super(text);
}
@Override
public void print() {
System.out.println("print Lable(" + text + ")");
}
}
class PasswordBox extends Component {
public PasswordBox(String text) {
super(text);
}
@Override
public void print() {
System.out.println("print PasswordBox(" + text + ")");
}
}
class CheckBox extends Component {
public CheckBox(String text) {
super(text);
}
@Override
public void print() {
System.out.println("print CheckBox(" + text + ")");
}
}
class TextBox extends Component {
public TextBox(String text) {
super(text);
}
@Override
public void print() {
System.out.println("print TextBox(" + text + ")");
}
}
class LinkLabel extends Component {
public LinkLabel(String text) {
super(text);
}
@Override
public void print() {
System.out.println("print LinkLabel(" + text + ")");
}
}
版权声明: 本文为 InfoQ 作者【铁血杰克】的原创文章。
原文链接:【http://xie.infoq.cn/article/142a54b8ef803f7d667218678】。未经作者许可,禁止转载。
评论 (1 条评论)