装饰模式

概述

代码示例

原本继承的方式

public interface Car {
	
	public void show();
	
	public void run();
}
public class RunCar implements Car {

	public void run() {
		System.out.println("可以跑");
	}

	public void show() {
		this.run();
	}

}
public class SwimCar implements Car{

	public void run() {
		System.out.println("可以跑");
	}

	public void Swim() {
		System.out.println("可以游");
	}
	
	public void show() {
		this.run();
		this.Swim();
	}

}

主函数

public class MainClass {
	public static void main(String[] args) {
		Car flycar = new SwimCar();
		flycar.show();
	}
}

装饰模式的

 

public interface Car {
	
	public void show();
	
	public void run();
}

基本的对象

public class RunCar implements Car {

	public void run() {
		System.out.println("可以跑");
	}

	public void show() {
		this.run();
	}

}

因为相对其扩展所以进行装饰

public abstract class CarDecorator implements Car{
	private Car car;
	
	public Car getCar() {
		return car;
	}

	public void setCar(Car car) {
		this.car = car;
	}

	public CarDecorator(Car car) {
		this.car = car;
	}
	
	public abstract void show();
}
public class FlyCarDecorator extends CarDecorator{

	public FlyCarDecorator(Car car) {
		super(car);
	}

	public void show() {
		this.getCar().show();
		this.fly();
	}
	
	public void fly() {
		System.out.println("可以飞");
	}

	public void run() {
		
	}
}

 

public class SwimCarDecorator extends CarDecorator {

	public SwimCarDecorator(Car car) {
		super(car);
	}

	public void show() {
		this.getCar().show();
		this.swim();
	}
	
	public void swim() {
		System.out.println("可以游");
	}

	public void run() {
		
	}

}
public class MainClass {
	public static void main(String[] args) {
		Car car = new RunCar();
		
		car.show();
		System.out.println("---------");
		
		Car swimcar = new SwimCarDecorator(car);
		swimcar.show();
		System.out.println("---------");
		
		Car flySwimCar = new FlyCarDecorator(swimcar);
		flySwimCar.show();
	}
}

 实现三个功能

这里原本只能跑的车可以飞和游泳了,就是因为装饰了不同的东西。

抽象组件角色:Car

具体组件角色:RunCar

抽象装饰角色:CarDecorator

具体装饰角色:FlyCarDecorator

Io里面的缓冲流就用到了这个模式。缓冲流