Java装饰器模式
装饰器
装饰器就是将原有的类功能加工新添新的功能
类图![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/37af0d07bceb1596f54b1194f2a5e8dd.png#pic_center)
Client为测试类;Vehicle为接口代表交通工具;MultiVehicle实现接口;VehicleDecorator是交通工具装饰器即附加给交通工具其他的功能,如飞行和航行;SwimVehicleDecorator为添加航行功能装饰器,FlyVehicleDecorator为添加飞行功能装饰器
public class Client {
public static void main(String[] args) {
/**
* Test1
*/
/*
Vehicle multiVehicle=new MultiVehicle();
multiVehicle.show();
System.out.println("----------------");
VehicleDecorator flyVehicleDecorator=
new FlyVehicleDecorator(multiVehicle);
flyVehicleDecorator.show();
*/
/**
* Test2
*/
Vehicle multiVehicle=new MultiVehicle();
multiVehicle.show();
System.out.println("----------------");
VehicleDecorator flyVehicleDecorator=
new FlyVehicleDecorator(multiVehicle);
flyVehicleDecorator.show();
System.out.println("----------------");
VehicleDecorator swimVehicleDecorator=
new SwimVehicleDecorator(multiVehicle);
swimVehicleDecorator.show();
}
}
public interface Vehicle {
public void show();
public void run();
}
public class MultiVehicle implements Vehicle {
@Override
public void show() {
this.run();
}
@Override
public void run() {
System.out.println("run on the road!");
}
}
public abstract class VehicleDecorator {
protected Vehicle vehicle;
public VehicleDecorator() {
}
public VehicleDecorator(Vehicle vehicle) {
this.vehicle = vehicle;
}
public Vehicle getVehicle() {
return vehicle;
}
public void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}
public abstract void show();
}
public class SwimVehicleDecorator extends VehicleDecorator{
public SwimVehicleDecorator() {
}
public SwimVehicleDecorator(Vehicle vehicle) {
this.vehicle=vehicle;
}
@Override
public Vehicle getVehicle() {
return vehicle;
}
@Override
public void setVehicle(Vehicle vehicle) {
this.vehicle=vehicle;
}
@Override
public void show() {
this.getVehicle().run();
this.swim();
}
public void swim(){
System.out.println("swimming is available!");
}
}
public class FlyVehicleDecorator extends VehicleDecorator {
public FlyVehicleDecorator() {
}
public FlyVehicleDecorator(Vehicle vehicle) {
this.vehicle=vehicle;
}
@Override
public Vehicle getVehicle() {
return vehicle;
}
@Override
public void setVehicle(Vehicle vehicle) {
this.vehicle=vehicle;
}
@Override
public void show() {
this.getVehicle().run();
this.fly();
}
public void fly(){
System.out.println("Fly is available!");
}
}