简单案例说明 :
package com.bjsxt.decorator;
/**
* 抽象构件
* @author Administrator
*
*/
public interface ICar {
void move();
}
//ConcreteComponent 具体构件角色(真实对象)
class Car implements ICar { //真正的要装饰的对象
@Override
public void move() {
System.out.println("陆地上跑!");
}
}
//Decorator装饰角色
class SuperCar implements ICar { //持有一个抽象构件的引用 ,要传参数(普通ICar对象)
protected ICar car; //子类可继承
public SuperCar(ICar car) {
super();
this.car = car;
}
@Override
public void move() {
car.move();
}
}
//ConcreteDecorator具体装饰角色
class FlyCar extends SuperCar { //继承具体构件,传参数(Icar),拥有具体构件的方法,并加以装饰
public FlyCar(ICar car) {
super(car);
}
public void fly(){
System.out.println("天上飞!");
}
@Override
public void move() {
super.move();
fly();
}
}
//ConcreteDecorator具体装饰角色
class WaterCar extends SuperCar {
public WaterCar(ICar car) {
super(car);
}
public void swim(){
System.out.println("水上游!");
}
@Override
public void move() {
super.move();
swim();
}
}
//ConcreteDecorator具体装饰角色
class AICar extends SuperCar {
public AICar(ICar car) {
super(car);
}
public void autoMove(){
System.out.println("自动跑!");
}
@Override
public void move() {
super.move();
autoMove();
}
}
package com.bjsxt.decorator;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Client {
public static void main(String[] args) {
Car car = new Car();
car.move();
System.out.println("增加新的功能,飞行----------");
FlyCar flycar = new FlyCar(car);
flycar.move();
System.out.println("增加新的功能,水里游---------");
WaterCar waterCar = new WaterCar(car);
waterCar.move();
System.out.println("增加两个新的功能,飞行,水里游-------");
WaterCar waterCar2 = new WaterCar(new FlyCar(car));
waterCar2.move();
// Reader r = new BufferedReader(new InputStreamReader(new FileInputStream(new File("d:/a.txt"))));
}
}