decorator模式 java_java设计模式-装饰模式Decorator

装饰者模式(Decorator Pattern)允许在不改变结构的情况下向已经存在的类添加新的功能。这种类型的设计模式给已存在的类进行包装,属于结构型模型。

该设计模式创建一个装饰者类包装最初的类,并在保持类签名完整的情况下提供增加的功能。

interface Shape {

void draw();

}

class Rectangle implements Shape {

@Override

public void draw() {

System.out.println("正方形");

}

}

class Circle implements Shape {

@Override

public void draw() {

System.out.println("圆形");

}

}

class Decorator implements Shape {

private Shape shape;

public Decorator(Shape shape) {

this.shape = shape;

}

@Override

public void draw() {

System.out.println("装饰前-----");

shape.draw();

System.out.println("装饰后-----");

}

}

public class Client {

public static void main(String<> args) {

Rectangle rectangle = new Rectangle();

rectangle.draw();

Shape shape = new Decorator(rectangle);

shape.draw();

}

}正方形

装饰前-----

正方形

装饰后-----

创建具体具体的装饰对象继承Decorator,起到给shape添加功能。

比如给其加上边框

class RedShapeDecorator extends Decorator {

public RedShapeDecorator(Shape shape) {

super(shape);

}

@Override

public void draw() {

System.out.println("装饰前-----");

shape.draw();

setRedBorder(shape);

System.out.println("装饰后-----");

}

private void setRedBorder(Shape decoratedShape) {

System.out.println("装饰红色边框");

}

}

public class Client {

public static void main(String<> args) {

Rectangle rectangle = new Rectangle();

rectangle.draw();

Shape shape = new Decorator(rectangle);

shape.draw();

RedShapeDecorator redShapeDecorator = new RedShapeDecorator(rectangle);

redShapeDecorator.draw();

}

}

装饰器模式的应用场景:

Decorator模式提供了更加灵活的向对象添加职责的方式,可以使用添加和分离的方法,用装饰在运行时刻增加和删除职责(继承不能做到这一点,继承的功能是静态的,不能动态增删,因此比静态继承更灵活)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值