UML图:
产品:
PanelProduct.java
package Builder;
import javax.swing.*;
public class PanelProduct extends JPanel {
JButton button;
JLabel label;
JTextField textField;
}
抽象生成器:
Builder.java
import javax.swing.JPanel;
//抽象生成器
public interface Builder {
public abstract void buildButton();
public abstract void buildLable();
public abstract void buildTextField();
public abstract JPanel getPanel();
}
具体生成器:
package Builder;
import javax.swing.*;
public class ConcreteBuilderOne implements Builder {
private PanelProduct panel;
ConcreteBuilderOne() {
panel = new PanelProduct();
}
@Override
public void buildButton() {
panel.button = new JButton("按钮");
}
@Override
public void buildLable() {
panel.label = new JLabel("标签");
}
@Override
public void buildTextField() {
panel.textField = new JTextField("文本框");
}
@Override
public JPanel getPanel() {
panel.add(panel.button);
panel.add(panel.label);
panel.add(panel.textField);
return panel;
}
}
package Builder;
import javax.swing.*;
public class ConcreteBuilderTwo implements Builder {
private PanelProduct pannel;//需要具体容器
public ConcreteBuilderTwo() {
pannel=new PanelProduct();
}
@Override
public void buildButton() {
pannel.button=new JButton("button");
}
@Override
public void buildLable() {
pannel.label=new JLabel("label");
}
@Override
public void buildTextField() {
pannel.textField=new JTextField("textField");
}
@Override
public JPanel getPanel() {
pannel.add(pannel.textField);
pannel.add(pannel.label);
pannel.add(pannel.button);
return pannel;
}
}
指挥者:
package Builder;
import javax.swing.JPanel;
//指挥者
public class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public JPanel constructProduct() {
builder.buildButton();
builder.buildLable();
builder.buildTextField();
JPanel product = builder.getPanel();
return product;
}
}
模式使用:
package Builder;
import javax.swing.*;
public class Application {
public static void main(String[] args) {
Builder builder = new ConcreteBuilderOne();
Director director = new Director(builder);
JPanel panel = director.constructProduct();
JFrame frameOne = new JFrame();
frameOne.add(panel);
frameOne.setBounds(12, 12, 200, 120);
frameOne.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frameOne.setVisible(true);
builder = new ConcreteBuilderTwo();
director = new Director(builder);
panel = director.constructProduct();
frameOne = new JFrame();
frameOne.add(panel);
frameOne.setBounds(212, 12, 200, 120);
frameOne.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frameOne.setVisible(true);
}
}