装饰模式decorator
也叫包装器模式,降低系统的耦合度,可以动态的删除和添加对象的职责
使具体装饰角色类独立化,可以对一个类多次装饰。代替继承,更加灵活,避免类型体系快速膨胀
1.使用场景
动态的为一个对象增加新的功能
如:IO流输入输出设计
2.核心角色
- 抽象构件角色component:真实对象和装饰对象的接口
- 具体构件角色(真实对象):实现抽象构件角色
- 装饰角色:实现抽象构件角色
- 具体装饰角色:继承装饰角色对真实对象添加新功能
3.实现代码
package com.liang.decorator;
/**
* 抽象构件
* @author Administrator
*
*/
public interface ComponentCar {
/**
* 功能:跑
*/
void run();
}
//ConcreteComponent具体构件(真实对象)
class Car implements ComponentCar{
@Override
public void run() {
System.out.println("基本原始功能:在地上跑");
}
}
//Decorator装饰角色
class DecoratorCar implements ComponentCar{
protected ComponentCar car;
public DecoratorCar(ComponentCar car) {
super();
this.car = car;
}
@Override
public void run() {
car.run();
}
}
//ConcreteDecorator具体装饰角色
class FlyCar extends DecoratorCar{
public FlyCar(ComponentCar car) {
super(car);
}
@Override
public void run() {
super.run();
fly();
}
//新功能
public void fly() {
System.out.println("新功能:在天上飞");
}
}
//ConcreteDecorator具体装饰角色
class AICar extends DecoratorCar{
public AICar(ComponentCar car) {
super(car);
}
@Override
public void run() {
super.run();
autoRun();
}
//新功能
public void autoRun() {
System.out.println("新功能:自动驾驶");
}
}
public class Client {
public static void main(String[] args) {
System.out.println("--------------原始汽车-------------");
Car car=new Car();
car.run();
System.out.println("-------------飞行汽车---------------");
FlyCar flyCar=new FlyCar(car);
flyCar.run();
System.out.println("-----------飞行自动驾驶汽车---------");
AICar flyAiCar=new AICar(flyCar);
flyAiCar.run();
}
}