类结构和对象结构:
1、抽象组件
public interface View {
public void draw();
}
2、树叶组件
public class Circle implements View{
@Override
public void draw() {
System.out.print("O");
}
}
public class Square implements View{
@Override
public void draw() {
System.out.println("口");
}
}
3、树枝组件
import java.util.ArrayList;
public class LinearLayout implements View{
public static final int HORIZONTAL=0;
public static final int VERTICAL=1;
private int orientation;
private ArrayList<View> views=new ArrayList<View>();
@Override
public void draw() {
if(orientation==HORIZONTAL){
for(View view:views){
view.draw();
}
}else{
for(View view:views){
System.out.print("\t");//制表,形成垂直布局的效果
view.draw();
System.out.print("\n");//换行
}
}
}
public void add(View view){
views.add(view);
}
public void remove(View view){
views.remove(view);
}
public void setOrientation(int orientation) {
this.orientation = orientation;
}
}
public static final int HORIZONTAL=0;
public static final int VERTICAL=1;
private int orientation;
private ArrayList<View> views=new ArrayList<View>();
@Override
public void draw() {
if(orientation==HORIZONTAL){
for(View view:views){
view.draw();
}
}else{
for(View view:views){
System.out.print("\t");//制表,形成垂直布局的效果
view.draw();
System.out.print("\n");//换行
}
}
}
public void add(View view){
views.add(view);
}
public void remove(View view){
views.remove(view);
}
public void setOrientation(int orientation) {
this.orientation = orientation;
}
}
4、消费者
public class Customer{
public static void main(String[] args) {
Circle circle=new Circle();
Circle circle2=new Circle();
Circle circle3=new Circle();
Square square=new Square();
Square square2=new Square();
Square square3=new Square();
LinearLayout layoutChild=new LinearLayout();//子布局
layoutChild.setOrientation(LinearLayout.VERTICAL);//垂直布局
layoutChild.add(square);
layoutChild.add(square2);
layoutChild.add(square3);
LinearLayout layout=new LinearLayout();//父布局,默认水平布局
layout.add(circle);
layout.add(circle2);
layout.add(circle3);
layout.add(layoutChild);
layout.draw();//绘制整个视图
System.out.println("--------删除子布局的一个树叶节点后---------");
layoutChild.remove(square2);
layout.draw();//再次绘制整个视图
}
}
5、运行结果