1. 程式人生 > >設計模式(九)合成

設計模式(九)合成

類結構和物件結構:

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、執行結果