核心:在原有类的基础上增加装饰类完成更加额外的功能
注意:和代理模式不同,装饰模式对客户端时透明的,需要外界传入被装饰的对象。而代理模式是在代理类里面创建对象,被代理类是不透明的,只关注功能是否实现。
import sun.security.provider.SHA;
import java.util.ArrayList;
public class Test{
public static void main(String[] args) {
Decorator decorator1 = new RedDecorator(new Circle());
Decorator decorator2 = new RedDecorator(new Rectangle());
decorator1.draw();
decorator2.draw();
}
}
//被装饰着接口
interface Shape{
void draw();
}
//具体被装饰者类
class Circle implements Shape{
public void draw(){
System.out.println("圆形");
}
}
class Rectangle implements Shape{
public void draw(){
System.out.println("矩形");
}
}
//抽象装饰者
abstract class Decorator implements Shape{
private Shape shape;
public Decorator(Shape shape){
this.shape = shape;
}
public void draw(){
shape.draw();
}
}
class RedDecorator extends Decorator {
public RedDecorator(Shape shape){
super(shape);
}
public void draw(){
System.out.print("我是红色");
super.draw();
}
}
class GreenDecorator extends Decorator {
public GreenDecorator(Shape shape){
super(shape);
}
public void draw(){
System.out.print("我是蓝色");
super.draw();
}
}