装饰器模式

核心:在原有类的基础上增加装饰类完成更加额外的功能

注意:和代理模式不同,装饰模式对客户端时透明的,需要外界传入被装饰的对象。而代理模式是在代理类里面创建对象,被代理类是不透明的,只关注功能是否实现。



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();

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值