装饰器模式

装饰器模式

内容参考 w3cschool

 

分类: 结构性设计模式

应用: 1L的水能用木桶盛放,也能用1L的铁桶盛放;一张相片可以用不同的相框进行装饰


目录

装饰器模式

UML类图

创建形状接口

创建形状的抽象修饰器

创建红色的边框修饰器

测试执行


UML类图

用户告诉不同的装饰器(红色、蓝色、绿色)去修饰不同的对象:Circle、Rectangle

 

创建形状接口

Shape

public interface Shape {
    /**
     * 绘制图形
     */
    void draw();
}

创建 形状实体类

Circle

public class Circle implements Shape{
    @Override
    public void draw() {
        System.out.println("[Shape-Circle]");
    }
}

Rectangle

public class Rectangle implements Shape{
    @Override
    public void draw() {
        System.out.println("[Shape-Rectangle]");
    }
}

创建形状的抽象修饰器

public abstract class ShapeDecorator implements Shape{
    protected Shape shapeDecorator;

    public ShapeDecorator(Shape shapeDecorator) {
        this.shapeDecorator = shapeDecorator;
    }

    @Override
    public void draw() {
        shapeDecorator.draw();
    }
}

创建红色的边框修饰器

public class RedShapeDecorator extends ShapeDecorator{
    public RedShapeDecorator(Shape shapeDecorator) {
        super(shapeDecorator);
    }

    @Override
    public void draw() {
        shapeDecorator.draw();
        setRedBorder(shapeDecorator);
    }

    private void setRedBorder(Shape shapeDecorator){
        System.out.println("<Border> Color Red");
    }
}

测试执行

public class ExecuteMain {
    public static void main(String[] args) {

        Shape circle = new Circle();
        Shape redCircle = new RedShapeDecorator(new Circle());
        Shape redRectangle = new RedShapeDecorator(new Rectangle());

        System.out.println("--------normal Circle--------");
        circle.draw();
        System.out.println("--------Red Border Circle--------");
        redCircle.draw();
        System.out.println("--------Red Border Rectangle--------");
        redRectangle.draw();
    }
}
--------normal Circle--------
[Shape-Circle]
--------Red Border Circle--------
[Shape-Circle]
<Border> Color Red
--------Red Border Rectangle--------
[Shape-Rectangle]
<Border> Color Red

Process finished with exit code 0

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值