http://sourcemaking.com/design_patterns/composite/java/2

nterface Component { void traverse(); }      // 1. "lowest common denominator" 

class Primitive implements Component { // 2. "Isa" relationship
private int value;
public Primitive( int val ) { value = val; }
public void traverse() { System.out.print( value + " " ); }
}

abstract class Composite implements Component { // 2. "Isa" relationship
private Component[] children = new Component[9]; // 3. Couple to interface
private int total = 0;
private int value;
public Composite( int val ) { value = val; }
public void add( Component c ) { children[total++] = c; } // 3. Couple to
public void traverse() { // interface
System.out.print( value + " " );
for (int i=0; i < total; i++)
children[i].traverse(); // 4. Delegation and polymorphism
} }

class Row extends Composite { // Two different kinds of "con-
public Row( int val ) { super( val ); } // tainer" classes. Most of the
public void traverse() { // "meat" is in the Composite
System.out.print( "Row" ); // base class.
super.traverse();
} }

class Column extends Composite {
public Column( int val ) { super( val ); }
public void traverse() {
System.out.print( "Col" );
super.traverse();
} }

public class CompositeDemo {
public static void main( String[] args ) {
Composite first = new Row( 1 ); // Row1
Composite second = new Column( 2 ); // |
Composite third = new Column( 3 ); // +-- Col2
Composite fourth = new Row( 4 ); // | |
Composite fifth = new Row( 5 ); // | +-- 7
first.add( second ); // +-- Col3
first.add( third ); // | |
third.add( fourth ); // | +-- Row4
third.add( fifth ); // | | |
first.add( new Primitive( 6 ) ); // | | +-- 9
second.add( new Primitive( 7 ) ); // | +-- Row5
third.add( new Primitive( 8 ) ); // | | |
fourth.add( new Primitive( 9 ) ); // | | +-- 10
fifth.add( new Primitive(10 ) ); // | +-- 8
first.traverse(); // +-- 6
} }

Row1 Col2 7 Col3 Row4 9 Row5 10 8 6
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值