首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

装饰模式例证(模仿修改船只用途)

2012-11-04 
装饰模式例子(模仿修改船只用途)模仿一次出海旅行中船只的用途的动态调整功能 写道package cn.decorator

装饰模式例子(模仿修改船只用途)
模仿一次出海旅行中船只的用途的动态调整功能 写道package cn.decorator;

/**
* 功能
* @author 姚伟楠
*
*/
public interface Function {
/**
* 干某一件事
*/
public void doSomeThing();
}

?

船 写道package cn.decorator;

/**
* 船
* @author 姚伟楠
*
*/
public class Ship implements Function {

@Override
public void doSomeThing() {
System.out.println("航行");
}

}

?

巨轮 写道package cn.decorator;

/**
* 巨轮
* @author 姚伟楠
*
*/
public class HugeShip extends Ship{
private Function func;
public HugeShip(Function func) {
this.func = func;
}
@Override
public void doSomeThing() {
func.doSomeThing();
}


}

?

载人用途巨轮 写道package cn.decorator;

/**
* A用途巨轮
* @author 姚伟楠
*
*/
public class HugeShipA extends HugeShip {

public HugeShipA(Function func) {
super(func);
}

@Override
public void doSomeThing() {
super.doSomeThing();
this.carryPassengers();

}

/**
* 载人
*/
private void carryPassengers() {
System.out.println("运输客人");

}

}

?

载物巨轮 写道package cn.decorator;

/**
* B用途巨轮
* @author 姚伟楠
*
*/
public class HugeShipB extends HugeShip {

public HugeShipB(Function func) {
super(func);
}

@Override
public void doSomeThing() {
super.doSomeThing();
this.carryPassengers();

}

/**
* 载物
*/
private void carryPassengers() {
System.out.println("运输物品");

}

}

?

旅行 写道package cn.decorator;

/**
* 旅行
* @author 姚伟楠
*
*/
public class Travel {

/**
* @param args
*/
public static void main(String[] args) {
Ship a=new Ship();//闲余船只
a.doSomeThing();
System.out.println();
Ship b=new HugeShip(new HugeShipA(new HugeShipB(a)));//将闲余船只a改为既载客又载物的船只b
b.doSomeThing();
System.out.println();
Ship c=new HugeShip(new HugeShipA(a));//将闲余船只a改为只载客的船只c
c.doSomeThing();
System.out.println();
Ship d=new HugeShip(new HugeShipB(a));//将闲余船只a改为只载物的船只d
d.doSomeThing();

}

}

?

热点排行